ssh.exec_command(cmd,bufsize,timeout) #exec_command参数使用只需要执行一次的命令,因为执行完该命令以后,shell会自动回到ssh初始连接的shell状态下,(表达不好,可以看官方文档。),stdin,out,err,对应shell下的标准输入,输出和错误。
ssh.invoke_shell() #在SSH server端创建一个交互式的shell,且可以按自己的需求配置伪终端,可以在invoke_shell()函数中添加参数配置。
def chanel_exe_cmd(ChanelSSHOb,cmd,t=0.1):
ChanelSSHOb.send(cmd)
ChanelSSHOb.send("\n")
time.sleep(t)
resp = ChanelSSHOb.recv(9999).decode("utf8")
print("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<")
print("Exec sshCmd: %s" % (cmd))
print("--------------------")
print("Exec Result: %s" % (resp))
print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n")
return resp
def creatSShConnectOb(ip_remote, port_remote, username, password):
print('---------- start to create SSH object')
print('Remote SSH Info:\n\'ip:%s port:%d username:%s password:%s\'\n' %(ip_remote, port_remote, username, password))
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(ip_remote, port_remote, username=username, password=password, timeout=60) # timeout protection
return ssh
except:
print('Warning:\nFist connect the ABC failed, now will retry!')
ssh.connect(ip_remote, port_remote, username=username, password=password, timeout=60) # timeout re-try
print('Error:\nAttempt to connect ABC failed!!! Please check the IP / port/ account / password.')
else:
print('Info:\nConnect remote ABC success.')
if __name__ == '__main__':
ssh = creatSShConnectOb(ABC1_ip,ABC_port,admin_user,admin_pwd)
chanelSSHOb = ssh.invoke_shell() #建立交互式的shell
sshCmd = 'whoami'
chanel_exe_cmd(chanelSSHOb, sshCmd)
sshCmd = 'ls -R -l ' + ABC_admin_remoteDir
chanel_exe_cmd(chanelSSHOb, sshCmd)
sshCmd = 'su'
if chanel_exe_cmd(chanelSSHOb, sshCmd).endswith(u"Password: "):
sshCmd = root_pwd
chanel_exe_cmd(chanelSSHOb, sshCmd)
sshCmd = 'whoami'
chanel_exe_cmd(chanelSSHOb, sshCmd)
sshCmd = r'docker ps | grep mp'
chanel_exe_cmd(chanelSSHOb, sshCmd)
sshCmd = 'rm -rf ' + ABC_admin_remoteDir + '*'
chanel_exe_cmd(chanelSSHOb, sshCmd)
refrence:
http://blog.chinaunix.net/uid-429659-id-3851967.html
https://blog.csdn.net/pengwupeng2008/article/details/82218388