python 使用paramiko模塊進(jìn)行封裝,遠(yuǎn)程操作linux主機(jī)的示例代碼
import timeimport paramikoclass HandleParamiko: ’’’ 定義一個(gè)linux處理類 ’’’ def __init__(self, hostname, password, port=22, username=’root’): ’’’ 構(gòu)造器 :param hostname: 主機(jī)ip,type:str :param password: 密碼,type:str :param port: 端口,type:int 默認(rèn)22 :param username: 用戶名,type:str :return: ’’’ self.t = None self.sftp = None self.hostname = hostname self.password = password self.port = port self.username = username self.client = paramiko.SSHClient() # 實(shí)例化SSHclient self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 自動(dòng)添加策略,保存服務(wù)器的主機(jī)名和密鑰信息 try: self.client.connect(hostname=hostname,port=port,username=username,password=password) except Exception as all: print(f'連接異常,請(qǐng)確認(rèn)參數(shù)是否有誤:{all}') self.channel = self.client.invoke_shell() # 創(chuàng)建一個(gè)交互會(huì)話的對(duì)象 def sftp_client(self): ’’’ 創(chuàng)建一個(gè)sftp上傳下載客戶端 :return: sftp對(duì)象,調(diào)用put()和get()分別實(shí)現(xiàn)文件的上傳和下載 ’’’ try: self.t = paramiko.Transport((self.hostname, self.port)) self.t.connect(username=self.username, password=self.password) self.sftp = paramiko.SFTPClient.from_transport(self.t) return self.sftp except FileNotFoundError as e: print(f'FileNotFoundError:{e}') def cmd_res(self, cmd, get_way=’out’): ’’’ 定義一個(gè)一次性會(huì)話方法(優(yōu)點(diǎn):響應(yīng)速度快,缺點(diǎn):不能保持會(huì)話) :param cmd: linux命令,type:str :param get_way: 支持:‘in’、‘out’、‘err’三種方式 :return: 回顯結(jié)果 ’’’ stdin, stdout, stderr = self.client.exec_command(cmd) if get_way == ’in’: return str(stdin.read()).replace(’n’, ’n’) elif get_way == ’out’: return str(stdout.read()).replace(’n’, ’n’) elif get_way == ’err’: return str(stderr.read()).replace(’n’, ’n’) else: print('輸入獲取的方式有誤,獲取回顯結(jié)果失敗!') def cmd_ssh(self, cmd): ’’’ 定義一個(gè)交互會(huì)話的方法(優(yōu)點(diǎn):交互式會(huì)話,缺點(diǎn):響應(yīng)速度慢) :param cmd: linux命令,type:str :return: ’’’ self.channel.send(cmd+’n’) time.sleep(5) try: res = self.channel.recv(1024 * 100000).decode(’utf-8’) except: res = self.channel.recv(1024 * 100000).decode(’gbk’) return res def close_channel(self): ’’’ 關(guān)閉交互式會(huì)話 :return: ’’’ self.channel.close() def close_client(self): ’’’ 關(guān)閉SSH連接 :return: ’’’ self.client.close()
以上就是python 使用paramiko模塊進(jìn)行封裝,遠(yuǎn)程操作linux主機(jī)的示例代碼的詳細(xì)內(nèi)容,更多關(guān)于python paramiko模塊的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
