python使用paramiko執(zhí)行服務器腳本并拿到實時結果
更新時間:2022年12月20日 08:56:17 作者:LanLanDeMing
這篇文章主要介紹了python使用paramiko執(zhí)行服務器腳本并拿到實時結果,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
paramiko 執(zhí)行服務器腳本并拿到實時結果
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遠程密碼連接
# 基于ssh用于連接遠程服務器做操作:遠程執(zhí)行命令, 上傳文件, 下載文件
import paramiko
# ssh root@172.25.254.250
# 創(chuàng)建一個ssh對象;
client = paramiko.SSHClient()
# 2. 解決問題:如果之前沒有;連接過的ip, 會出現(xiàn)
# Are you sure you want to continue connecting (yes/no)? yes
# 自動選擇yes
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 3. 連接服務器
client.connect(hostname='172.25.254.1',
port=22,
username='root',
password='redhat')
# 4. 執(zhí)行操作
stdin, stdout, stderr = client.exec_command('hostnaewdeme')
# 5. 獲取命令的執(zhí)行結果;
result = stdout.read().decode('utf-8')
print(result)
print(stderr.read())
# 6. 關閉連接
client.close()
paramiko批量遠程密碼連接
# 基于ssh用于連接遠程服務器做操作:遠程執(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)建一個ssh對象;
client = paramiko.SSHClient()
# 2. 解決問題:如果之前沒有;連接過的ip, 會出現(xiàn)
# Are you sure you want to continue connecting (yes/no)? yes
# 自動選擇yes
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
# 3. 連接服務器
client.connect(hostname=hostname,
port=port,
username=username,
password=password)
print("正在連接主機%s......." %(hostname))
except NoValidConnectionsError as e:
print("連接失敗")
except AuthenticationException as e:
print("密碼錯誤")
else:
# 4. 執(zhí)行操作
stdin, stdout, stderr = client.exec_command(cmd)
# 5. 獲取命令的執(zhí)行結果;
result = stdout.read().decode('utf-8')
print(result)
# 6. 關閉連接
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用于連接遠程服務器做操作:遠程執(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)建一個ssh對象;
client = paramiko.SSHClient()
# 返回一個私鑰對象
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
# 自動選擇yes
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
# 3. 連接服務器
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("密碼錯誤")
else:
# 5. 獲取命令的執(zhí)行結果;
result = stdout.read().decode('utf-8')
print(result)
finally:
# 6. 關閉連接
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
# 返回一個私鑰對象
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):
"""默認調用的內容"""
# 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)建一個ssh對象;
client = paramiko.SSHClient()
# 2. 解決問題:如果之前沒有;連接過的ip, 會出現(xiàn)
# Are you sure you want to continue connecting (yes/no)? yes
# 自動選擇yes
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
# 3. 連接服務器
client.connect(hostname=self.hostname,
port=self.port,
username=self.user,
password=self.passwd)
print("正在連接主機%s......." % (self.hostname))
except NoValidConnectionsError as e:
print("連接失敗")
except AuthenticationException as e:
print("密碼錯誤")
else:
# 4. 執(zhí)行操作
# cmd uname
# cmd ls /etc/
# *******注意:
cmd = ' '.join(self.cmd.split()[1:])
stdin, stdout, stderr = client.exec_command(cmd)
# 5. 獲取命令的執(zhí)行結果;
result = stdout.read().decode('utf-8')
print(result)
# 6. 關閉連接
client.close()
def do_put(self):
# put /tmp/passwd /tmp/passwd
# put /tmp/passwd /tmp/pwd
# put /tmp/passwd # 將本機的/tmp/passwd文件上傳到遠程主機的/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主機的%s文件成功" %(newCmd[0],
self.hostname, newCmd[1]))
else:
print("上傳文件信息錯誤")
transport.close()
def do_get(self):
print("正在下載.....")
# 2. 根據(jù)選擇的主機組, 顯示包含的主機IP/主機名;
# 3. 讓用戶確認信息, 選擇需要批量執(zhí)行的命令;
# - cmd shell命令
# - put 本地文件 遠程文件
# - get 遠程文件 本地文件
def main():
# 1. 選擇操作的主機組:eg: mysql, web, ftp
groups = [file.rstrip('.conf') for file in os.listdir('conf')]
print("主機組顯示:".center(50, '*'))
for group in groups: print('\t', group)
choiceGroup = input("清選擇批量操作的主機組(eg:web):")
# 2. 根據(jù)選擇的主機組, 顯示包含的主機IP/主機名;
# 1). 打開文件conf/choiceGroup.conf
# 2). 依次讀取文件每一行,
# 3). 只拿出ip
print("主機組包含主機:".center(50, '*'))
with open('conf/%s.conf' %(choiceGroup)) as f:
for line in f:
print(line.split(':')[0])
f.seek(0,0) # 把指針移動到文件最開始
hostinfos = [line.strip() for line in f.readlines()]
# 3. 讓用戶確認信息, 選擇需要批量執(zhí)行的命令;
print("批量執(zhí)行腳本".center(50, '*'))
while True:
cmd = input(">>:").strip() # cmd uname
if cmd:
if cmd == 'exit' or cmd =='quit':
print("執(zhí)行結束, 退出中......")
break
# 依次讓該主機組的所有主機執(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()總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Django部署到服務器后無法獲取到靜態(tài)元素 The requested resource
寫了一個Django項目,部署到云主機后,訪問發(fā)現(xiàn)圖片無法訪問,報錯The requested resource was not found on this server,下面給大家介紹Django部署到服務器后無法獲取到靜態(tài)元素The requested resource was not found on this server(問題及解決方案),需要的朋友可以參考下2024-02-02
詳解Django-restframework 之頻率源碼分析
這篇文章主要介紹了Django-restframework 之頻率源碼分析,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-02-02

