依賴包:pip install paramiko
源碼demo:
from time import *
import paramiko
# 定義一個(gè)類,表示一臺(tái)遠(yuǎn)端linux主機(jī)
class Linux(object):
# 通過IP, 用戶名,密碼,超時(shí)時(shí)間初始化一個(gè)遠(yuǎn)程Linux主機(jī)
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 = ''
# 鏈接失敗的重試次數(shù)
self.try_times = 3
# 調(diào)用該方法連接遠(yuǎn)程主機(jī)
def connect(self):
while True:
# 連接過程中可能會(huì)拋出異常,比如網(wǎng)絡(luò)不通、鏈接超時(shí)
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)
# 接收到的網(wǎng)絡(luò)數(shù)據(jù)解碼為str
print(self.chan.recv(65535).decode('utf-8'))
return
# 這里不對(duì)可能的異常如socket.error, socket.timeout細(xì)化,直接一網(wǎng)打盡
except Exception as e1:
if self.try_times != 0:
print('連接%s失敗,進(jìn)行重試' % self.ip)
self.try_times -= 1
else:
print('重試3次失敗,結(jié)束程序')
exit(1)
# 斷開連接
def close(self):
self.chan.close()
self.t.close()
# 發(fā)送要執(zhí)行的命令
def send(self, cmd):
cmd += '\r'
result = ''
# 發(fā)送要執(zhí)行的命令
self.chan.send(cmd)
# 回顯很長的命令可能執(zhí)行較久,通過循環(huán)分批次取回回顯,執(zhí)行成功返回true,失敗返回false
while True:
sleep(0.5)
ret = self.chan.recv(65535)
ret = ret.decode('utf-8')
result += ret
return result
'''
發(fā)送文件
@:param upload_files上傳文件路徑 例如:/tmp/test.py
@:param upload_path 上傳到目標(biāo)路徑 例如:/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') # 發(fā)送一個(gè)查看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"))
? |
? ? ? ? |
運(yùn)行代碼測(cè)試效果圖:
以上這篇python3模擬實(shí)現(xiàn)xshell遠(yuǎn)程執(zhí)行l(wèi)iunx命令的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

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