需要使用python远程连接防火墙,使用paramiko远程连接并远程执行shell指令报错:
调用的代码如下:
def ssh_normal(remote_ip,ssh_port,user_name,passs_word,cmd):
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(remote_ip,username=user_name,password=passs_word,allow_agent=True)
stdin, stdout, stderr = ssh.exec_command(cmd)
print stdout.readlines()
print stderr.readlines()
except Exception, e:
print e
finally:
ssh.close()
在执行
ssh.exec_command(cmd)
时,报错:Max try count must be an positive integer。不太清楚报错的原因,可能是安全策略的原因,改为以下代码后可以顺利连通并远程执行命令:
def ssh(remote_ip,username,password,cmds,port=22):
client = paramiko.SSHClient()
result=""
try:
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(remote_ip, port, username, password, timeout=20)
remote_conn = client.invoke_shell()
for cmd in cmds:
remote_conn.send('\n')
time.sleep(delay)
remote_conn.send(cmd)
time.sleep(delay)
remote_conn.send('\n')
time.sleep(delay)
result+=str(remote_conn.recv(buffer_size))
except Exception, e:
print e
result=str(e)
finally:
client.close()
return result