def exe_sshcmd(ip,username,userpswd,port,cmd):
? ? """
? ? 功能:SSH登錄到指定設備,并執行對應的命令
? ? 入參:前四項為ssh登錄shell的ip和port,具備管理員權限的用戶名和密碼,
? ? ? ? ? cmd可以是單條命令,也可以是命令列表
? ? 返回:每次命令執行結果列表,標準輸出結果,不包含錯誤輸出
? ? Examples:
? ? |Exe Sshcmd| ip|name|pswd|cmd|
? ? """
? ? try:
? ? ? ? ssh_client = paramiko.SSHClient()
? ? ? ? ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
? ? ? ? ssh_client.connect(ip, int(port), username, userpswd)
? ? ? ? ret=[]
? ? ? ? if isinstance(cmd, list):
? ? ? ? ? ? cmd = ";".join(cmd)
? ? ? ? print('exe command:',cmd)
? ? ? ? stdin, stdout, stderr=ssh_client.exec_command("%s"%cmd,timeout=30)
? ? ? ? ret=stdout.read()
? ? ? ? retcode = stdout.channel.recv_exit_status()
? ? ? ? print('exe command return info:\n',str(ret,encoding="gbk"))
? ? ? ? print('exe command return code:',stdout.channel.recv_exit_status())
? ? ? ? if stdout.channel.recv_exit_status()!=0:
? ? ? ? ? ? print('stderr:',str(stderr.read(),encoding='gbk'))
? ? ? ? ssh_client.close()
? ? ? ? return bytes.decode(ret).strip(),retcode
? ? except Exception as err:
? ? ? ? print(err)
? ? ? ? print("ssh connect failed(ip=%s,user=%s,pwd=%s,port=%d)." %(ip,username,userpswd,int(port)))
? ? ? ? return "ssh connect fail",1