python使用paramiko執(zhí)行服務(wù)器腳本并拿到實(shí)時(shí)結(jié)果
更新時(shí)間:2022年12月20日 08:56:17 作者:LanLanDeMing
這篇文章主要介紹了python使用paramiko執(zhí)行服務(wù)器腳本并拿到實(shí)時(shí)結(jié)果,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
paramiko 執(zhí)行服務(wù)器腳本并拿到實(shí)時(shí)結(jié)果
import paramiko cmd = '{0}/{1} linux 32'.format('/root/installer', 'make_client_installer.sh') print(cmd) try: ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect('xx.xx.xx.xx', port, 'username', 'password', timeout=5) stdin, stdout, stderr = ssh.exec_command(cmd, get_pty=True) while not stdout.channel.exit_status_ready(): result = stdout.readline() print(result) if stdout.channel.exit_status_ready(): a = stdout.readlines() print(a) break ssh.close() except Exception as e: print(e)```
python paramiko模塊使用
paramiko遠(yuǎn)程密碼連接
# 基于ssh用于連接遠(yuǎn)程服務(wù)器做操作:遠(yuǎn)程執(zhí)行命令, 上傳文件, 下載文件 import paramiko # ssh root@172.25.254.250 # 創(chuàng)建一個(gè)ssh對象; client = paramiko.SSHClient() # 2. 解決問題:如果之前沒有;連接過的ip, 會出現(xiàn) # Are you sure you want to continue connecting (yes/no)? yes # 自動(dòng)選擇yes client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 3. 連接服務(wù)器 client.connect(hostname='172.25.254.1', port=22, username='root', password='redhat') # 4. 執(zhí)行操作 stdin, stdout, stderr = client.exec_command('hostnaewdeme') # 5. 獲取命令的執(zhí)行結(jié)果; result = stdout.read().decode('utf-8') print(result) print(stderr.read()) # 6. 關(guān)閉連接 client.close()
paramiko批量遠(yuǎn)程密碼連接
# 基于ssh用于連接遠(yuǎn)程服務(wù)器做操作:遠(yuǎn)程執(zhí)行命令, 上傳文件, 下載文件 import paramiko import logging from paramiko.ssh_exception import NoValidConnectionsError, AuthenticationException def connect(cmd, hostname, port=22, username='root', password='westos'): # ssh root@172.25.254.250 # 創(chuàng)建一個(gè)ssh對象; client = paramiko.SSHClient() # 2. 解決問題:如果之前沒有;連接過的ip, 會出現(xiàn) # Are you sure you want to continue connecting (yes/no)? yes # 自動(dòng)選擇yes client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: # 3. 連接服務(wù)器 client.connect(hostname=hostname, port=port, username=username, password=password) print("正在連接主機(jī)%s......." %(hostname)) except NoValidConnectionsError as e: print("連接失敗") except AuthenticationException as e: print("密碼錯(cuò)誤") else: # 4. 執(zhí)行操作 stdin, stdout, stderr = client.exec_command(cmd) # 5. 獲取命令的執(zhí)行結(jié)果; result = stdout.read().decode('utf-8') print(result) # 6. 關(guān)閉連接 client.close() with open('host.txt') as f: for line in f: line = line.strip() hostname, port, username, password = line.split(':') print(hostname.center(50, '*')) connect('hostname', hostname, port, username, password)
paramiko基于公鑰密鑰連接
# 基于ssh用于連接遠(yuǎn)程服務(wù)器做操作:遠(yuǎn)程執(zhí)行命令, 上傳文件, 下載文件 import paramiko from paramiko.ssh_exception import NoValidConnectionsError, AuthenticationException def connect(cmd, hostname, port=22, user='root'): # ssh root@172.25.254.250 # 創(chuàng)建一個(gè)ssh對象; client = paramiko.SSHClient() # 返回一個(gè)私鑰對象 private_key = paramiko.RSAKey.from_private_key_file('id_rsa') # 2. 解決問題:如果之前沒有;連接過的ip, 會出現(xiàn) # Are you sure you want to continue connecting (yes/no)? yes # 自動(dòng)選擇yes client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: # 3. 連接服務(wù)器 client.connect(hostname=hostname, port=port, username=user, pkey=private_key ) # 4. 執(zhí)行操作 stdin, stdout, stderr = client.exec_command(cmd) except NoValidConnectionsError as e: print("連接失敗") except AuthenticationException as e: print("密碼錯(cuò)誤") else: # 5. 獲取命令的執(zhí)行結(jié)果; result = stdout.read().decode('utf-8') print(result) finally: # 6. 關(guān)閉連接 client.close() for count in range(254): host = '172.25.254.%s' %(count+1) print(host.center(50, '*')) connect('uname', host)
基于用戶名密碼上傳下載
import ?paramiko transport = paramiko.Transport(('172.25.254.39', 22)) transport.connect(username='root', password='westos') sftp = paramiko.SFTPClient.from_transport(transport) # 上傳文件, 包含文件名 sftp.put('/tmp/kiosk', '/mnt/kiosk1') sftp.get('/mnt/kiosk', '/home/kiosk/Desktop/day18/kiosk') transport.close()
基于密鑰上傳下載
import ?paramiko # 返回一個(gè)私鑰對象 private_key = paramiko.RSAKey.from_private_key_file('id_rsa') transport = paramiko.Transport(('172.25.254.39', 22)) transport.connect(username='root',pkey=private_key) sftp = paramiko.SFTPClient.from_transport(transport) # 上傳文件, 包含文件名 sftp.put('/tmp/kiosk', '/mnt/kiosk2') sftp.get('/mnt/kiosk2', '/home/kiosk/Desktop/day18/kiosk') transport.close()
paramiko再次封裝
import os import paramiko from paramiko.ssh_exception import NoValidConnectionsError, AuthenticationException, SSHException class SshRemoteHost(object): def __init__(self, hostname, port, user, passwd, cmd): # 指的不是shell命令 # cmd shell命令 # put # get self.hostname = hostname self.port = port self.user = user self.passwd = passwd self.cmd = cmd def run(self): """默認(rèn)調(diào)用的內(nèi)容""" # cmd hostname # put # get cmd_str = self.cmd.split()[0] # cmd # 類的反射, 判斷類里面是否可以支持該操作? if hasattr(self, 'do_'+ cmd_str): # do_cmd getattr(self, 'do_'+cmd_str)() else: print("目前不支持該功能") def do_cmd(self): # 創(chuàng)建一個(gè)ssh對象; client = paramiko.SSHClient() # 2. 解決問題:如果之前沒有;連接過的ip, 會出現(xiàn) # Are you sure you want to continue connecting (yes/no)? yes # 自動(dòng)選擇yes client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: # 3. 連接服務(wù)器 client.connect(hostname=self.hostname, port=self.port, username=self.user, password=self.passwd) print("正在連接主機(jī)%s......." % (self.hostname)) except NoValidConnectionsError as e: print("連接失敗") except AuthenticationException as e: print("密碼錯(cuò)誤") else: # 4. 執(zhí)行操作 # cmd uname # cmd ls /etc/ # *******注意: cmd = ' '.join(self.cmd.split()[1:]) stdin, stdout, stderr = client.exec_command(cmd) # 5. 獲取命令的執(zhí)行結(jié)果; result = stdout.read().decode('utf-8') print(result) # 6. 關(guān)閉連接 client.close() def do_put(self): # put /tmp/passwd /tmp/passwd # put /tmp/passwd /tmp/pwd # put /tmp/passwd # 將本機(jī)的/tmp/passwd文件上傳到遠(yuǎn)程主機(jī)的/tmp/passwd; print("正在上傳.....") try: transport = paramiko.Transport((self.hostname, int(self.port))) transport.connect(username=self.user, password=self.passwd) except SSHException as e: print("連接失敗") else: sftp = paramiko.SFTPClient.from_transport(transport) newCmd = self.cmd.split()[1:] if len(newCmd) == 2: # 上傳文件, 包含文件名 sftp.put(newCmd[0], newCmd[1]) print("%s文件上傳到%s主機(jī)的%s文件成功" %(newCmd[0], self.hostname, newCmd[1])) else: print("上傳文件信息錯(cuò)誤") transport.close() def do_get(self): print("正在下載.....") # 2. 根據(jù)選擇的主機(jī)組, 顯示包含的主機(jī)IP/主機(jī)名; # 3. 讓用戶確認(rèn)信息, 選擇需要批量執(zhí)行的命令; # - cmd shell命令 # - put 本地文件 遠(yuǎn)程文件 # - get 遠(yuǎn)程文件 本地文件 def main(): # 1. 選擇操作的主機(jī)組:eg: mysql, web, ftp groups = [file.rstrip('.conf') for file in os.listdir('conf')] print("主機(jī)組顯示:".center(50, '*')) for group in groups: print('\t', group) choiceGroup = input("清選擇批量操作的主機(jī)組(eg:web):") # 2. 根據(jù)選擇的主機(jī)組, 顯示包含的主機(jī)IP/主機(jī)名; # 1). 打開文件conf/choiceGroup.conf # 2). 依次讀取文件每一行, # 3). 只拿出ip print("主機(jī)組包含主機(jī):".center(50, '*')) with open('conf/%s.conf' %(choiceGroup)) as f: for line in f: print(line.split(':')[0]) f.seek(0,0) # 把指針移動(dòng)到文件最開始 hostinfos = [line.strip() for line in f.readlines()] # 3. 讓用戶確認(rèn)信息, 選擇需要批量執(zhí)行的命令; print("批量執(zhí)行腳本".center(50, '*')) while True: cmd = input(">>:").strip() # cmd uname if cmd: if cmd == 'exit' or cmd =='quit': print("執(zhí)行結(jié)束, 退出中......") break # 依次讓該主機(jī)組的所有主機(jī)執(zhí)行 for info in hostinfos: # 'ip:port:user:passwd' host, port, user, passwd = info.split(":") print(host.center(50, '-')) clientObj = SshRemoteHost(host, port, user, passwd, cmd) clientObj.run() if __name__ == '__main__': main()
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Django部署到服務(wù)器后無法獲取到靜態(tài)元素 The requested resource
寫了一個(gè)Django項(xiàng)目,部署到云主機(jī)后,訪問發(fā)現(xiàn)圖片無法訪問,報(bào)錯(cuò)The requested resource was not found on this server,下面給大家介紹Django部署到服務(wù)器后無法獲取到靜態(tài)元素The requested resource was not found on this server(問題及解決方案),需要的朋友可以參考下2024-02-02Pandas數(shù)據(jù)清洗的實(shí)現(xiàn)
在處理數(shù)據(jù)的時(shí)候,需要對數(shù)據(jù)進(jìn)行一個(gè)清洗過程,本文就來介紹一下Pandas數(shù)據(jù)清洗的實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下2023-11-11詳解Django-restframework 之頻率源碼分析
這篇文章主要介紹了Django-restframework 之頻率源碼分析,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-02-02python交互模式基礎(chǔ)知識點(diǎn)學(xué)習(xí)
在本篇內(nèi)容里小編給大家整理的是關(guān)于python交互模式是什么的相關(guān)基礎(chǔ)知識點(diǎn),需要的朋友們可以參考下。2020-06-06