1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
# -*- coding: utf-8 -*- #!/usr/bin/env python import pexpect,os #导入需要用到模块
def ssh_cmd(ip, shell_cmd):
passwd = '1qaz#EDC'
print 'host: %s is connected... ' % ip
child = pexpect.spawn( 'ssh root@%s' % (ip))
fout = file ( 'log.txt' , 'a' )
child.logfile = fout
try :
i = child.expect( 'password:' )
if i = = 0 :
child.sendline(passwd) elif i = = 1 :
child.sendline( 'yes\n' )
child.expect( 'password: ' )
child.sendline(passwd) print 'host:%s Login ok!' % ip
child.expect( '#' )
child.sendline(shell_cmd) #执行传过来的shell命令
child.expect( '#' )
print 'host:%s Command Execution ok!' % ip
except pexpect.EOF:
print "Command run ok!"
child.close() except pexpect.TIMEOUT:
print "Connect Timeout..."
child.close() #前面的ssh_cmd()作用为建立ssh连接 for i in range ( 165 , 167 ):
ipaddr = '192.168.122.%s' % i
ssh_cmd(ipaddr, 'mkdir -p /etc/ceph' ) #ssh连接上远程主机后,在远程主机创建制定目录
os.environ[ 'ip' ] = str (ipaddr) #python变量和shell变量互用
os.system( 'sshpass -p 1qaz#EDC scp /home/testfile*.conf root@$ip:/etc/ceph' ) #文件下发
|
本文转自 TtrToby 51CTO博客,原文链接:http://blog.51cto.com/freshair/1903000