近期,需要实现一些功能,通过python去控制远程linux,这里就接触到了paramiko模块
这里有挺多小技巧和大家一起分享下
1.通过SSH去连接远程服务器
由于如果linux host/user等不对,都会引起连接时候的异常,所以我么可以捕获下异常
def connectLinux(self,remoteDict:dict) -> bool:
#checkDict valid
for ii in range(len(self.linuxKeyPara)):
if self.linuxKeyPara[ii] not in remoteDict:
return False
self.SSHClient = paramiko.SSHClient()
self.SSHClient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
self.SSHClient.connect(hostname=remoteDict["host"], port=remoteDict["port"], username=remoteDict["username"], password=remoteDict["pwd"]) # 通过SSH连接到linux
self.ssh_transp = self.SSHClient.get_transport()
return True
except BaseException as e:
print(e)
return False
2.通过SSH去控制Linux时,经常遇到以下异常,通过查找资料以及实际测试发现,这个其实是由于发送的命令还没有执行完成导致的问题,可采用如下的code来规避
Paramiko “TypeError: ‘NoneType’ object is not callable” at the end of a script that execute command on the server
def execCmd(self,cmd:str,cmdTime=1) -> (str,str):
if self.SSHClient is not None:
chan = self.ssh_transp.open_session()
chan.exec_command(cmd)
outdata, errdata = "", ""
sleeptime = 0.001
cnt = 0
while 1:
if cnt >= 800: #防止长时间无响应
break
while chan.recv_ready():
outdata += chan.recv(1000).decode()
while chan.recv_stderr_ready():
errdata += chan.recv_stderr(1000).decode()
if chan.exit_status_ready():
break
time.sleep(sleeptime)
cnt += 1
return outdata, errdata
最主要的是第二个坑,调试了很久
不过我的主要任务是连接上,控制好之后关于p4 cmd的操作,这里项目相关,不贴出来,有需要的交流的可以留言