shell及python脚本方式登陆服务器

1、问题java

在工做过程当中,常常会碰见须要登陆服务器,而且由于安全的缘由,须要使用交互的方式登陆,并且shell、python在工做中也常常用到,而且能够提供交互的功能。都是利用了expect、spawn、send、interact等命令。python

2、实现shell

一、shell方式安全

#!/usr/bin/expect -f
set timeout 1
spawn ssh -A iwill@192.168.0.101
expect "Password:"
send "123456\r"
interact

二、python方式服务器

#! /usr/bin/python

import sys
import pexpect

def servers_name():
   servers = ['sample_app_one','sample_app_two']
   return servers

def sample_app_one_ips():
    tcs_ips = ['192.168.0.101','192.168.0.102']
    return tcs_ips

def sample_app_two_ips():
    bsn_ips = ['192.168.0.101','192.168.0.102']
    return bsn_ips

def connect_server(ip):
    cmd="ssh root@{}".format(ip)
    child = pexpect.spawn(cmd)
    child.expect ('password:')     
    child.sendline('123456')
    child.interact()

def main():
 print "server list show below : "
 servers=servers_name()
 index = 0
 for server in servers:
    index = index + 1
    print '%d : %s'%(index,server)
 show_msg='please select server(1...%d) : '%index
 server_index = input(show_msg)
 server_name=servers[server_index-1]
 print 'the %s ips are below : '%server_name
 server_ips_cmd= 'ips=%s_ips()'%server_name
 exec(server_ips_cmd)
 #print server_ips_cmd
 #ips=tcs_dubbo_ips()
 index = 0
 for ip in ips :
     index = index +1
     print '%d : %s'%(index,ip)
 show_msg='please select ip(i...%d) : '%index
 ip_index = input(show_msg)
 ip=ips[ip_index-1]
 connect_server(ip)

if __name__=="__main__":
   main()

3、扩展app

写这些脚本,能够锻炼本身的脚本能力。ssh

相关文章
相关标签/搜索