python登录脚本及图形化_shell及python脚本方式登录服务器

一、问题

在工作过程中,经常会遇见需要登录服务器,并且因为安全的原因,需要使用交互的方式登录,而且shell、python在工作中也经常用到,并且可以提供交互的功能。都是利用了expect、spawn、send、interact等命令。

二、实现

1、shell方式

#!/usr/bin/expect -f

set timeout 1

spawn ssh -A iwill@192.168.0.101

expect "Password:"

send "123456\r"

interact

2、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()

三、扩展

写这些脚本,可以锻炼自己的脚本能力。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值