-
#[root@localhost ~]# cat login.exp
-
#! /usr/bin/expect
-
##by Lightman
-
set ipaddress [lindex $argv 0] //设置ipaddress变量,采用参数0
-
set password [lindex $argv 1] //设置ipaddress变量,采用参数0
-
spawn ssh ii@$ipaddress //spwan 激活ssh程序进行交互式运行
-
expect {
-
"yes/no" {send "yes\r"} //捕捉yes/no的字符串,并发送send命令
-
"*assword:" {send "$password\r"} //捕捉*assword的字符串,并发送send命令
-
}
-
expect "]*" //捕捉shell提示符($、#)
-
send "date\r"
-
send "sleep 5\r"
-
#send "su - ii\r"
-
send "su - root\r"
-
expect "*assword:"
-
send "echo\“hello \” >> /root/temp.txt\r" //send 传送命令时,如遇到有双引号之类的 ,要用 "\" 进行转义
-
send "sleep 5\r"
-
send "exit\r"
-
send "sleep 5\r"
-
send "exit\r"
-
interact //terminal保持停留在当前服务器
都是从网上找的,总结一下
一.
使用shell脚本中的except方法,脚本如下
--------转载自
Kayson的博客
二.
python的pexpect模块(感觉不如用shell)
三.
python的paramiko模块(这个好用),代码如下
-
#-*- 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\tOK\n'%(ip)
-
-
ssh.close()
-
-
except :
-
-
print '%s\tError\n'%(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()
阅读(1154) | 评论(1) | 转发(0) |