用的昨天刚接触到的库,在windows下通过paramiko来登录linux系统并执行了几个命令,基本算是初试成功,后面会接着学习的。
代码:
>>> import paramiko
>>> ssh = paramiko.SSHClient()
>>> ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
>>> ssh.connect('10.104.6.8',username = 'xiaopeng',password='******')
>>> cmd = 'cd' #进入用户目录home
>>> stdin,stdout,stderr = ssh.exec_command(cmd)
>>> cmd = 'ls >test' #管道,ls命名的输出到文件test里面
>>> stdin,stdout,stderr = ssh.exec_command(cmd)
>>> cmd = 'cat test' # 显示test的内容,即ls命名的结果
>>> stdin,stdout,stderr = ssh.exec_command(cmd)
>>> print stdout.readlines() #结果 汉字用的字符显示
['code
', 'Desktop
', 'order.cpp
', 'python
', 'test
', 'xe5x85xacxe5x85xb1xe7x9ax84
', 'xe6xa8xa1xe6x9dxbf
', 'xe8xa7x86xe9xa2x91
', 'xe5x9bxbexe7x89x87
', 'xe6x96x87xe6xa1xa3
', 'xe4xb8x8bxe8xbdxbd
', 'xe9x9fxb3xe4xb9x90
']
这里我们都会发现,使用exec_command('cd dirname')时并不会切换目录,execute_command() 是a single session,每次执行完后都要回到缺省目录。所以可以 .execute_command('cd /var; pwd')。
python里面的paramiko模块,用这个实现ssh登录更加简单。看下面的代码:
- #-*- coding: utf-8 -*-
- #!/usr/bin/python
- import paramiko
- import threading
- def ssh2(ip,username,passwd,cmd):
- try:
- ssh = paramiko.SSHClient()
- ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
- ssh.connect(ip,22,username,passwd,timeout=5)
- for m in cmd:
- stdin, stdout, stderr = ssh.exec_command(m)
- # stdin.write("Y") #简单交互,输入 ‘Y’
- out = stdout.readlines()
- #屏幕输出
- for o in out:
- print o,
- print '%s OK '%(ip)
- ssh.close()
- except :
- print '%s Error '%(ip)
- if __name__=='__main__':
- cmd = ['cal','echo hello!']#你要执行的命令列表
- username = "" #用户名
- passwd = "" #密码
- threads = [] #多线程
- print "Begin......"
- for i in range(1,254):
- ip = '192.168.1.'+str(i)
- a=threading.Thread(target=ssh2,args=(ip,username,passwd,cmd))
- a.start()
上面的程序还是有些技巧的:
1.利用多线程,同时发出登录请求,同时去连接电脑,这样速度快很多,我试了一下,如果不用多线程,直接一个一个挨着执行的话,大约5~10秒钟才能对一台电脑操作完,具体时间要根据命令的来决定,如果是软件安装或者卸载时间要更长一些。这样下来怎么也要一二十分钟,用多线程后就快多了,所有的命令执行完用了不到2分钟!
2.最好用root用户登录,因为安装或者卸载软件的时候如果用普通用户又会提示输入密码,这样又多了一次交互,处理起来就比较麻烦!安装软件时apt-get install xxx 最好加上“-y”参数,因为有时安装或删除软件时提示是否继续安装或卸载,这又是一次自动交互!加上那个参数后就没有人机交互了。
3. 循环时循环所有ip,因为计算机的ip是路由器自动分配的,保险起见,最好全部都执行,保证没有遗漏的主机
4.远端执行命令时如果有交互,可以这样用 stdin.write("Y")来完成交互,“Y”就是输入“Y”。
5.把所有的命令放到一个列表里面,遍历列表可以依次执行列表里面的命令
6.为了更好的进行控制,最好在电脑上提前把root用户打开,装好ssh服务器并让其开机自动执行。
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('10.111.43.18',22,'root','12345',timeout=5)
stdin, stdout, stderr = ssh.exec_command('cd /root/epoll/')
stdin, stdout, stderr = ssh.exec_command('pwd')
上边的代码输出应该是 /root/epoll/,但结果却是 /root ,即使用root登陆的缺省目录
原因是exec_command为单个会话,执行完成之后会回到登录时的缺省目录
修改为这样执行结果则为预期的 /root/epoll 目录
stdin, stdout, stderr = ssh.exec_command('cd /root/epoll/;pwd')
最近闲着学习python,看到有个paramiko模块,貌似很强大,学着写了个一个小程序,可以直接在window下登录到linux,执行并返回执行结果。
下面直接贴代码:
#!/usr/bin/env python import paramiko #hostname='192.168.0.102' hostname='172.28.102.250' username='root' password='abc' #port=22 if __name__=='__main__': paramiko.util.log_to_file('paramiko.log') s=paramiko.SSHClient() #s.load_system_host_keys() s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) s.connect(hostname = hostname,username=username, password=password) stdin,stdout,stderr=s.exec_command('ifconfig;free;df -h') print stdout.read() s.close()
下面看下效果,呵呵:
s501914252.HCA-FW9CX2XDesktop学习资料python paramiko-ssh.py" eth0 Link encap:Ethernet HWaddr 00:24:01:01:EA:5C inet addr:172.32.34.240 Bcast:172.32.255.255 Mask:255.255.255.0 UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:1428 errors:0 dropped:0 overruns:0 frame:0 TX packets:2 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:190928 (186.4 KiB) TX bytes:128 (128.0 b) Interrupt:20 eth1 Link encap:Ethernet HWaddr 00:1F:29:03:54:3D inet addr:172.28.102.250 Bcast:172.28.255.255 Mask:255.255.0.0 UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:99698 errors:0 dropped:0 overruns:0 frame:0 TX packets:12305 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:36420324 (34.7 MiB) TX bytes:923630 (901.9 KiB) lo Link encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 UP LOOPBACK RUNNING MTU:16436 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:0 (0.0 b) TX bytes:0 (0.0 b) peth1 Link encap:Ethernet HWaddr FE:FF:FF:FF:FF:FF UP BROADCAST RUNNING NOARP MTU:1500 Metric:1 RX packets:99686 errors:0 dropped:0 overruns:0 frame:0 TX packets:12333 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:36818715 (35.1 MiB) TX bytes:1006230 (982.6 KiB) Interrupt:20 Memory:f3000000-f3010000 vif0.1 Link encap:Ethernet HWaddr FE:FF:FF:FF:FF:FF UP BROADCAST RUNNING NOARP MTU:1500 Metric:1 RX packets:12305 errors:0 dropped:0 overruns:0 frame:0 TX packets:99702 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:923630 (901.9 KiB) TX bytes:36420811 (34.7 MiB) vif1.0 Link encap:Ethernet HWaddr FE:FF:FF:FF:FF:FF UP BROADCAST RUNNING NOARP MTU:1500 Metric:1 RX packets:5 errors:0 dropped:0 overruns:0 frame:0 TX packets:85175 errors:0 dropped:542 overruns:0 carrier:0 collisions:0 txqueuelen:500 RX bytes:140 (140.0 b) TX bytes:20377326 (19.4 MiB) vif2.0 Link encap:Ethernet HWaddr FE:FF:FF:FF:FF:FF UP BROADCAST RUNNING NOARP MTU:1500 Metric:1 RX packets:5 errors:0 dropped:0 overruns:0 frame:0 TX packets:84859 errors:0 dropped:411 overruns:0 carrier:0 collisions:0 txqueuelen:500 RX bytes:140 (140.0 b) TX bytes:20301953 (19.3 MiB) vif3.0 Link encap:Ethernet HWaddr FE:FF:FF:FF:FF:FF UP BROADCAST RUNNING NOARP MTU:1500 Metric:1 RX packets:5 errors:0 dropped:0 overruns:0 frame:0 TX packets:84337 errors:0 dropped:546 overruns:0 carrier:0 collisions:0 txqueuelen:500 RX bytes:140 (140.0 b) TX bytes:20174994 (19.2 MiB) virbr0 Link encap:Ethernet HWaddr 00:00:00:00:00:00 inet addr:192.168.122.1 Bcast:192.168.122.255 Mask:255.255.255.0 UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:0 (0.0 b) TX bytes:0 (0.0 b) xenbr1 Link encap:Ethernet HWaddr FE:FF:FF:FF:FF:FF UP BROADCAST RUNNING NOARP MTU:1500 Metric:1 RX packets:86405 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:19498121 (18.5 MiB) TX bytes:0 (0.0 b) total used free shared buffers cached Mem: 3359744 464724 2895020 0 31096 246296 -/+ buffers/cache: 187332 3172412 Swap: 5406712 0 5406712 Filesystem Size Used Avail Use% Mounted on /dev/mapper/VolGroup00-LogVol00 221G 25G 185G 12% / /dev/sda1 99M 22M 73M 23% /boot tmpfs 1.8G 0 1.8G 0% /dev/shm none 1.8G 152K 1.8G 1% /var/lib/xenstored
-、执行远程命令:
#!/usr/bin/python
#coding:utf-8
import paramiko
port =22
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect("*.*.*.*",port,"username", "password")
stdin, stdout, stderr = ssh.exec_command("你的命令")
print stdout.readlines()
ssh.close()
二、上传文件到远程
#!/usr/bin/python
#coding:utf-8
import paramiko
port =22
t = paramiko.Transport(("IP",port))
t.connect(username = "username", password = "password")
sftp = paramiko.SFTPClient.from_transport(t)
remotepath='/tmp/test.txt'
localpath='/tmp/test.txt'
sftp.put(localpath,remotepath)
t.close()
三、从远程下载文件
#!/usr/bin/python
#coding:utf-8
import paramiko
port =22
t = paramiko.Transport(("IP",port))
t.connect(username = "username", password = "password")
sftp = paramiko.SFTPClient.from_transport(t)
remotepath='/tmp/test.txt'
localpath='/tmp/test.txt'
sftp.get(remotepath, localpath)
t.close()
四、执行多个命令
#!/usr/bin/python
#coding:utf-8
import sys
sys.stderr = open('/dev/null') # Silence silly warnings from paramiko
import paramiko as pm
sys.stderr = sys.__stderr__
import os
class AllowAllKeys(pm.MissingHostKeyPolicy):
def missing_host_key(self, client, hostname, key):
return
HOST = '127.0.0.1'
USER = ''
PASSWORD = ''
client = pm.SSHClient()
client.load_system_host_keys()
client.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
client.set_missing_host_key_policy(AllowAllKeys())
client.connect(HOST, username=USER, password=PASSWORD)
channel = client.invoke_shell()
stdin = channel.makefile('wb')
stdout = channel.makefile('rb')
stdin.write('''
cd tmp
ls
exit
''')
print stdout.read()
stdout.close()
stdin.close()
client.close()
五、获取多个文件
#!/usr/bin/python
#coding:utf-8
import paramiko
import os
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('localhost',username='****')
apath = '/var/log'
apattern = '"*.log"'
rawcommand = 'find {path} -name {pattern}'
command = rawcommand.format(path=apath, pattern=apattern)
stdin, stdout, stderr = ssh.exec_command(command)
filelist = stdout.read().splitlines()
ftp = ssh.open_sftp()
for afile in filelist:
(head, filename) = os.path.split(afile)
print(filename)
ftp.get(afile, './'+filename)
ftp.close()
ssh.close()
paramiko模块是基于Python实现的ssh远程安全链接,实现命令远程、文件传输、SSH代理等功能。本文详细介绍了paramiko模块常用的方法,且实用价值非常高,稍作修改就能做出一个实用的运维工具。
安装
letong@me:~$ sudo pip install paramiko
简单的远程执行命令实例
#!/usr/bin/env python import paramiko hostname='127.0.0.1' username='root' password='123456' port=2222 ssh=paramiko.SSHClient() ssh.load_system_host_keys() ssh.connect(hostname=hostname,port=port,username=username,password=password) stdin,stdout,stderr=ssh.exec_command('ls /') print stdout.read() ssh.close()
SSHClient类
SSHClient类是SSH服务会话的高级表示,封装了传输、通道以及SFTPClient的校验、建立方法,通常用于执行命令。
connect方法
connect(self, hostname, port=22, username=None, password=None, pkey=None, Key_filename=None, timeout=None, allow_agent=True, look_for_keys=True, compress=False)
参数说明:
hostname,连接目标的主机地址 port,连接目标的端口,默认22 username,用户名 password,用户密码 pkey,私钥方式用户验证 key_filename,私钥文件名 timeout,超时时间 allow_agent,是否允许ssh代理 look_for_keys,是否允许搜索私钥文件 compress,打开时是否压缩
exec_command方法
exec_command(self, command, bufzise=-1)
参数说明:
command,执行的命令 bufsize,文件缓冲区大小,-1不限制
load_system_host_keys方法
load_system_host_keys(self, filename=None)
参数说明:
filename,指定远程主机公钥文件
set_missing_host_key_policy方法
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
参数说明:
AutoAddPolicy,自动添加主机名及密钥到本地并保存,不依赖load_system_host_keys()配置 RejectPolicy,自动拒绝未知主机名和密钥,依赖load_system_host_keys()配置 WarnningPolicy,功能与AutoAddPolicy相同,但是未知主机会报警
SFTPClient类
根据SSH传输协议的sftp会话,实现远程文件上传、下载等操作。
from_transport方法
from_transport(cls, t)
参数说明:
t,一个已通过验证的传输对象
例:
>>> import paramiko >>> a = paramiko.Transport((“127.0.0.1″,2222)) >>> a.connect(username=”root”, password=’123456′) >>> sftp = paramiko.SFTPClient.from_transport(a)
put方法
put(self, localpath, remotepath, callback=None, confirm=True)
参数说明:
localpath,上传源文件的本地路径 remotepath,目标路径 callback,获取接收与总传输字节数 confirm,上传完毕后是否调用stat()方法,以便确认文件大小
例:
>>> localpath=’ftp-test.log’ >>> remotepath=’/data/ftp-test.log’ >>> sftp.put(localpath,remotepath)
get方法
get(self, remotepath, localpath, callback=None)
参数说明:
remotepath,需要下载的远程文件 localpath,本地存储路径 callback,同put方法
其他方法
mkdir,用于创建目录 remove,删除目录 rename,重命名 stat,获取文件信息 listdir,获取目录列表