python之paramiko
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python之paramiko相关的知识,希望对你有一定的参考价值。
[[email protected] auto_maintance]# cat paramiko_key.py
#!/usr/bin/env python
# function: remote multi exec cmd by ssh.
# version:1.1
import paramiko
import socket
import sys,os
host = sys.argv[1]
user = sys.argv[2]
port = int(sys.argv[3])
authen_method = sys.argv[4]
if authen_method == ‘PASSWORD‘:
password = sys.argv[5]
cmd = sys.argv[6]
else:
cmd = sys.argv[5]
ss = paramiko.SSHClient()
ss.load_system_host_keys()
ss.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#pkey_file = ‘/home/alex/.ssh/id_rsa‘
#key = paramiko.RSAKey.from_private_key_file(pkey_file)
#s.connect(host,port,username,pkey=key,timeout=5)
try:
if authen_method == ‘SSH_KEY‘:
pkey_file = ‘/root/.ssh/id_rsa‘
key = paramiko.RSAKey.from_private_key_file(pkey_file)
ss.connect(host,port,user,pkey=key,timeout=5)
elif authen_method == ‘PASSWORD‘:
ss.connect(host,port,user,password,timeout=5)
stdin,stdout,stderr = s.exec_command(cmd)
cmd_result = stdout.read(),stderr.read()
print "--------Result from: %s -------" % host
for line in cmd_result:
print line,
ss.close()
except paramiko.AuthenticationException:
print "\033[31;1m%s Authentication Error!\033[0m" % host
except socket.error:
print "\033[31;1m%s Connection Refused!\033[0m" % host
以上是关于python之paramiko的主要内容,如果未能解决你的问题,请参考以下文章
python linux交互模块(paramikofabric与pexpect)