依賴包:pip install paramiko
源碼demo:
from time import *
import paramiko
# 定義一個類,表示一臺遠端linux主機
class Linux(object):
# 通過IP, 用戶名,密碼,超時時間初始化一個遠程Linux主機
def __init__(self, ip, username, password, timeout=30):
self.ip = ip
self.username = username
self.password = password
self.timeout = timeout
# transport和chanel
self.t = ''
self.chan = ''
# 鏈接失敗的重試次數
self.try_times = 3
# 調用該方法連接遠程主機
def connect(self):
while True:
# 連接過程中可能會拋出異常,比如網絡不通、鏈接超時
try:
self.t = paramiko.Transport(sock=(self.ip, 22))
self.t.connect(username=self.username, password=self.password)
self.chan = self.t.open_session()
self.chan.settimeout(self.timeout)
self.chan.get_pty()
self.chan.invoke_shell()
# 如果沒有拋出異常說明連接成功,直接返回
print('連接%s成功' % self.ip)
# 接收到的網絡數據解碼為str
print(self.chan.recv(65535).decode('utf-8'))
return
# 這里不對可能的異常如socket.error, socket.timeout細化,直接一網打盡
except Exception as e1:
if self.try_times != 0:
print('連接%s失敗,進行重試' % self.ip)
self.try_times -= 1
else:
print('重試3次失敗,結束程序')
exit(1)
# 斷開連接
def close(self):
self.chan.close()
self.t.close()
# 發送要執行的命令
def send(self, cmd):
cmd += '\r'
result = ''
# 發送要執行的命令
self.chan.send(cmd)
# 回顯很長的命令可能執行較久,通過循環分批次取回回顯,執行成功返回true,失敗返回false
while True:
sleep(0.5)
ret = self.chan.recv(65535)
ret = ret.decode('utf-8')
result += ret
return result
'''
發送文件
@:param upload_files上傳文件路徑 例如:/tmp/test.py
@:param upload_path 上傳到目標路徑 例如:/tmp/test_new.py
'''
def upload_file(self,upload_files,upload_path):
try:
tran=paramiko.Transport(sock=(self.ip, self.port))
tran.connect(username=self.username, password=self.password)
sftp = paramiko.SFTPClient.from_transport(tran)
result=sftp.put(upload_files, upload_path)
return True if result else False
except Exception as ex:
print(ex)
tran.close()
finally:
tran.close()
# 連接正常的情況
if __name__ == '__main__':
host = Linux('192.168.16.57', 'root', '+B*A15*EFpKG') # 傳入Ip,用戶名,密碼
host.connect()
# result = host.send('ls') # 發送一個查看ip的命令
def input_cmd(str):
return input(str)
tishi_msg="輸入命令:"
while True:
msg=input(tishi_msg)
if msg=="exit":
host.close()
break
else:
res=host.send(msg)
data=res.replace(res.split("\n")[-1],"")
tishi_msg=res.split("\n")[-1]
print(res.split("\n")[-1] + data.strip("\n"))
? |
? ? ? ? |
運行代碼測試效果圖:
以上這篇python3模擬實現xshell遠程執行liunx命令的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
