免密码登录服务器python脚本

在自动化运维平台没有做完之前,常需要登录服务器做很多维护操作,每次找好长好长的密码,那么多服务器,你会疯掉的,所以瞎搞了以下脚本.先解一下燃眉之急,哈哈

cat login_root.exp

#!/usr/bin/expect -c

set IP [lindex $argv 0]
set PWD [lindex $argv 1]
set timeout 2
spawn ssh root@$IP
expect "*yes/no*" {send "yes
"}
expect "*assword*" {send "$PWD
";interact}

用下面脚本调用 /opt/.script/login_root.exp 脚本,登录你需要登录的服务器

cat  login_remote.py
#!/usr/bin/env python
#author:wangqiankun@lashou-inc.com
#name:login_remote.py 

import re,time
import sys
import commands
import subprocess

def login_main(ip,pwd):
if ip != "" and pwd != "":
    print "33[32;1m start login at:%s33[0m" %time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    p = subprocess.call("expect /opt/.script/troot.exp %s '%s'" %(ip,pwd),shell=True)

else:
    print "33[32;1m IP or the password is wrong, please handle 33[0m"


def re_ip(ipinfo):
with open('/root/.script/password.txt','r') as f:
    for ipline in f.readlines():
    hostinfo = re.match(r'^192.168.%s .*' %ipinfo,ipline,re.M|re.I)
    if hostinfo:
        print "33[32;1m You are going to the login server IP is:%s33[0m" %hostinfo.group().split()[0]
        return hostinfo.group().split()[0],hostinfo.group().split()[1]




if __name__ == "__main__":
try:
    ipinfo = sys.argv[1].strip()
    if ipinfo != "":
    hostinfo = re_ip(ipinfo)
    try:
        login_main(hostinfo[0],hostinfo[1])
    except TypeError:
        print "33[31;1mThere is no matching to the correct IP address 33[0m"
except IndexError:
    print "33[31;1m You do not need to log in to the IP information input33[0m"
#print ipinfo,

测试:

  python login_remote.py 10.100

原文地址:https://www.cnblogs.com/shantu/p/4598884.html