這里發一個自己圖省事搞的一個批量打通SSH的腳本,可能對於好多朋友也是實用的,是expect+python的一個組合實現,原理非常easy, 使用起來也不復雜,在此還是簡單貼出來說說。
noscp.exp
#!/usr/bin/expect
#noscp.exp
if {$argc<4} {
puts stderr "Usage: $argv0 localfile remotefile user passwd "
exit 1
}
set localfile [ lindex $argv 0 ]
set remotefile [ lindex $argv 1 ]
set user [ lindex $argv 2 ]
set pwd [ lindex $argv 3 ]
set timeout 30
spawn scp ${localfile} ${user}@${remotefile}
expect {
"*yes/no" { send "yes\r"; exp_continue }
"*password:" { send "$pwd\r" }
}
expect eof
ssh_distribute.py
#!/usr/bin/python
import subprocess
import os
file_dir='/home/hosts'
with open(file_dir) as data:
for each_line in data.readlines():
if each_line != '':
(ip,passwd)=each_line.split(':',2)
print('./noscp.exp ~/.ssh/authorized_keys '+ip+':~/.ssh '+'root '+passwd.strip('\n'))
subprocess.Popen('./noscp.exp ~/.ssh/authorized_keys '+ip+':~/.ssh '+'root '+passwd.strip('\n'),shell=True)
# subprocess.Popen('./sshkey.exp '+ip+' root '+passwd+' \\| grep ssh-rsa >> ~/.ssh/authorized_keys',shell=True)
else:
pass
#subprocess.Popen('chmod 755 ~/.ssh/authorized_keys',shell=True)
ssh_setup.py
#!/usr/bin/python
import subprocess
import os
file_dir='/home/hosts'
with open(file_dir) as data:
for each_line in data.readlines():
if each_line != '':
(ip,passwd)=each_line.split(':',2)
print('./sshkey.exp '+ip+' root '+passwd.strip('\n')+' | grep ssh-rsa >> ~/.ssh/authorized_keys')
subprocess.Popen('./sshkey.exp '+ip+' root '+passwd.strip('\n')+' | grep ssh-rsa >> ~/.ssh/authorized_keys',shell=True)
# subprocess.Popen('./sshkey.exp '+ip+' root '+passwd+' \\| grep ssh-rsa >> ~/.ssh/authorized_keys',shell=True)
else:
pass
subprocess.Popen('chmod 755 ~/.ssh/authorized_keys',shell=True)
#subprocess.Popen('/home/ssh_distribute.py',shell=True)
sshkey.exp
#!/usr/bin/expect
#sshkey.exp
if {$argc<3} {
puts stderr "Usage: $argv0 host user passwd "
exit 1
}
set host [ lindex $argv 0 ]
set user [ lindex $argv 1 ]
set pwd [ lindex $argv 2 ]
set timeout 30
#spawn ssh ${user}@${host} "rm -rf ~/.ssh/id_rsa*"
#
#expect {
# "*yes/no" { send "yes\r"; exp_continue }
# "*password:" { send "$pwd\r"; exp_continue }
#}
spawn ssh ${user}@${host} "ssh-keygen -t rsa"
expect {
"*yes/no" { send "yes\r"; exp_continue }
"*password:" { send "$pwd\r"; exp_continue }
"Enter file in which to save the key*" { send "\n\r"; exp_continue }
"Overwrite*" { send "y\n"; exp_continue }
"Enter passphrase (empty for no passphrase):" { send "\n\r"; exp_continue }
"Enter same passphrase again:" { send "\n\r" }
}
spawn ssh ${user}@${host} "cat ~/.ssh/id_rsa.pub"
expect {
"*yes/no" { send "yes\r"; exp_continue }
"*password:" { send "$pwd\r" }
}
expect eof
多看兩眼代碼應該能夠看出,expect的功能是能夠等待一些Linux反饋 通過這個的反饋做出推斷並能夠分類進行興許的動作,非常黃非常暴力。
也就是利用了這個原理。過程例如以下: 1.首先運行 ./ssh_setup.py 首先收集全部機器的公鑰,然后定向到運行這個腳本的authorized_keys文件中邊,自己主動賦予755權限。 2.運行./ssh_distribute.py 分發authorized_keys文件到全部的機器上。
下載連接在下方,詳細用法里邊有readme.txt
http://download.csdn.net/detail/u012886375/9453810