python脚本之paramiko
#############################################################安装paramiko
[root@LVS1 ~]# yum install GCc
[root@LVS1 ~]#tar -zxvf pycrypto-2.6.1.tar.gz#https://pypi.python.org/pypi/pycrypto
[root@LVS1 ~]#cd pycrypto-2.6.1
[root@LVS1 pycrypto-2.6.1]#Python setup.py install
[root@LVS1 ~]# yum install python-devel
[root@LVS1 ~]#tar -zxvf paramiko-1.10.1.tar.gz#Https://pypi.python.org/pypi/paramiko
[root@LVS1 ~]#cd paramiko-1.10.1
[root@LVS1 paramiko-1.10.1]# python setup.py install
[root@LVS1 demos]# python demo.py 192.168.1.10#测试
##################################################################使用密码登陆
#!/usr/bin/env python
#coding=utf-8
import paramiko
#远程服务器
hostname ='192.168.1.10'
#端口
port=22
#用户名
username='root'
#密码?
passWord = '123456'
#创建ssh连接日志文件(只保留前一次连接的详细日志,以前的日志会自动被覆盖
#paramiko.util.log_to_file('paramiko.log')
s = paramiko.SSHClient()
#允许连接不在know_hosts文件中的主机
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#建立SSH连接
s.connect(hostname,port,username,password)
stdin,stdout,stderr=s.exec_command('top -bn 1')
#打印标准输出
print stdout.read()
s.close()
#########################################################使用key登陆
#!/usr/bin/env python
#coding=utf-8
import paramiko
hostname ='192.168.1.11'
port=22
username='root'
key_file='/root/.ssh/id_rsa'
key=paramiko.RSAKey.from_private_key_file(key_file)
#paramiko.util.log_to_file('paramiko.log')
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
s.load_system_host_keys()
s.connect(hostname,port,username,pkey=key)
stdin,stdout,stderr=s.exec_command('df -m')
print stdout.read()
print stderr.read()
s.close()
########################################手动输入命令多次执行
#!/usr/bin/env python
#coding=utf-8
import paramiko
hostname ='192.168.1.11'
port=22
username='root'
key_file='/root/.ssh/id_rsa'
key=paramiko.RSAKey.from_private_key_file(key_file)
#paramiko.util.log_to_file('paramiko.log')
s = paramiko.SSHClient()
#s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
s.load_system_host_keys()
s.connect(hostname,port,username,pkey=key)
while True:
cmd=raw_input('cmd:')
if cmd=='quit':break
stdin,stdout,stderr=s.exec_command(cmd)
print stdout.read()
print stderr.read()
s.close()
相关文章