您的位置:首页 > 运维架构 > Shell

利用shell + python + expect实现类似xshell功能(测试环境:ubuntu)

2014-04-05 19:48 836 查看
摘要: 该软件实现环境是ubuntu,具有基本的增加和删除ip的功能,有gui版和非gui版

#各个脚本的功能介绍
#meanue.sh 主要登陆框架
#mk_key_filec python实现的将用户信息编码存放,最初想法是加密,这块以后优化为加密
#zenity ubuntu自带的msg窗口(大概是这样滴。。。)
#auto_ssh.sh 自动登陆远程服务器脚本
#login_ssh 这是一个expect脚本,实现登陆功能

下面分别给出每个脚本的代码:

meanue.sh:
#!/bin/sh

#Name:meanue.sh
#Version:v1.3
#Author:Linux-c
#Date:2014-03-01

trap _exit 2
config=$HOME/sbin/.passwd
key_file=$HOME/sbin/.key.dat
mk_pass=$HOME/sbin/mk_key_filec

clear_file()
{
rm -f $config info.$$$$
}

_exit()
{
clear_file
exit
}

mk_key()
{
rm -f $key_file
`python $mk_pass -t encode -i $config -o $key_file`
return 0
}

un_key()
{
`python $mk_pass -t decode -i $key_file -o $config `
return 0
}

add_user()
{
echo ""
echo -n "Ip:"
read ip
echo -n "User:"
read user
echo -n "Password:"
read passwd
echo $ip $user $passwd >>$config
mk_key
return
}

add_user_gui()
{
title='Auto Login v1.0'
text='Please write ip '
wide=200
high=100
zenity --title="$title" --text="$text" --window-icon="" \
--width=$wide --height=$high --entry 1>info.$$$$ 2>/dev/null
ip="`cat info.$$$$`"
zenity --title="$title" --window-icon="" \
--width=$wide --height=$high --password --username 1>info.$$$$ 2>/dev/null
user="`cat info.$$$$|cut -d"|" -f1`"
passwd="`cat info.$$$$|cut -d"|" -f2`"
echo $ip $user $passwd >>$config
mk_key
return
}

del_user_gui()
{
title='Auto Login v1.0'
text='Please Choose Delete Ip '
wide=200
high=200
login_info="`cat $config|awk '{print $1}'`"
zenity --title="$title" --window-icon="" \
--width=$wide --height=$high --list \
--text="$text" \
--column=index $login_info  \
--hide-header=1 1>info.$$$$ 2>/dev/null
option="`cat info.$$$$`"
sed -i "/$option/d" $config
mk_key
return 0
}
del_user()
{
echo -n "请选择删除主机编号:"
read option
case $option in
[0-9]*) id=$option
echo -n "确认删除" `awk '{
if(NR=='"$id"')
printf("%s\n",$1)
}' $config`"的配置信息吗?(Y/N)"
read anws
echo $anws
if [ "$anws" = "Y" -o "$anws" = "y" ]
then
sed -i "${id}d" $config
mk_key
else
return 0
fi
;;
q|Q|quit|QUIT|exit|EXIT) return 0
;;
esac
return 0
}

main_gui()
{
un_key >/dev/null
clear

if [ "$config" = "" ]
then
echo "生成主机信息失败!"
fi
add="Add a new user!"
del="Delete a new user!"
high=300
wide=500
title='Auto Login v1.0'
text='Please Choose Login Ip From This List'

login_info="`cat $config|awk '{print $1}'`"
zenity --title="$title" --window-icon="" \
--width=$wide --height=$high --list \
--text="$text" \
--column=index $login_info "$add"  "$del" \
--hide-header=1 1>info.$$$$ 2>/dev/null
option="`cat info.$$$$|awk '{print $1}'`"

case $option in
[0-9]*) #ip=`awk '{if(NR=="'$option'") print $1}' $config`
auto_ssh.sh $option
[ $? -eq 2 ]&&echo "No record!Please add new user!"&&sleep 1&&main
;;
Delete) del_user_gui&&main_gui
;;
Add) add_user_gui&&main_gui
;;
q|Q|quit|QUIT|exit|EXIT) _exit ;;
esac
}

main()
{
un_key >/dev/null
clear

if [ "$config" = "" ]
then
echo "生成主机信息失败!"
fi

awk '{printf("\t%d:%s\n",++i,$1)}END{printf("\tn:新增主机\n\td:删除主机信息\n")}' $config
echo -n "请选择需要登陆的主机:"
read option

case $option in
[0-9]*) ip=`awk '{if(NR=="'$option'") print $1}' $config`
auto_ssh.sh $ip
[ $? -eq 2 ]&&echo "No record!Please add new user!"&&sleep 1&&main
;;
d) del_user&&main
;;
n) add_user&&main
;;
q|Q|quit|QUIT|exit|EXIT) _exit ;;
esac
}

chk_gui()
{
flag=`whereis zenity`
if [ ${#flag} -gt 8 ]
then
return 1
fi
return 0
}

chk_gui
result=$?

if [ $result -eq 1 ]
then
main_gui
else
main
fi
_exit


mk_key_filec 是mk_key_file脚本编译成的
编译代码如下:
#!/usr/bin/python
import py_compile
import sys

py_compile.compile(sys.argv[1])

mk_key_file代码如下:

#!/usr/bin/python
#-*- ecoding= utf-8 -*-
import os
import sys
import base64
import getopt

def usage():
print """
python %s -t encode -i inputfile -o outputfile
-t : encode make key file
decode make source file
-i :input file name
-o :out put file name
""" % sys.argv[0]
sys.exit(0)

def chk_file(file_name):
if os.path.exists(file_name):
return True
else:
return False

def encode(flag,i_file,o_file):

if chk_file(i_file):
i_fd=open(i_file,'r')
else:
usage

if not chk_file(o_file):
o_fd=open(o_file,'a')
else:
print "Warning:%s is exist,Delete it before run this programe!" % o_file
sys.exit(0)

if flag == 'encode':
encode_lines=base64.encodestring(i_fd.read()) # 对字符串编码
o_fd.write(encode_lines)
elif flag == 'decode':
decode_lines=base64.decodestring(i_fd.read()) # 对字符串解码
o_fd.write(decode_lines)
else:
usage

i_fd.close()
o_fd.close()

def main():
try:
flag=''
inputfile=''
outputfile=''
opts, args = getopt.getopt(sys.argv[1:], "t:i:o:h",\
["help","type=","infile=","outfile="])
for opt,arg in opts:
if opt in ("-h","--help"):
usage()
elif opt in ("-t","--type"):
flag=arg
elif opt in ("-i","--infile"):
inputfile=arg
elif opt in ("-o","--outfile"):
outputfile=arg
else:
assert False ,"unhandled option"
if flag == '' or inputfile =='' or outputfile=='':
usage()
else :
encode(flag,inputfile,outputfile)
except getopt.GetoptError:
usage()

if __name__ == '__main__':
main()
nantian@nantian-ThinkPad-Edge-E430:~/sbin$ vi mk_key_file
nantian@nantian-ThinkPad-Edge-E430:~/sbin$ cat mk_key_file
#!/usr/bin/python
#-*- ecoding= utf-8 -*-
import os
import sys
import base64
import getopt

def usage():
print """
python %s -t encode -i inputfile -o outputfile
-t : encode make key file
decode make source file
-i :input file name
-o :out put file name
""" % sys.argv[0]
sys.exit(0)

def chk_file(file_name):
if os.path.exists(file_name):
return True
else:
return False

def encode(flag,i_file,o_file):

if chk_file(i_file):
i_fd=open(i_file,'r')
else:
usage

if not chk_file(o_file):
o_fd=open(o_file,'a')
else:
print "Warning:%s is exist,Delete it before run this programe!" % o_file
sys.exit(0)

if flag == 'encode':
encode_lines=base64.encodestring(i_fd.read()) # 对字符串编码
o_fd.write(encode_lines)
elif flag == 'decode':
decode_lines=base64.decodestring(i_fd.read()) # 对字符串解码
o_fd.write(decode_lines)
else:
usage

i_fd.close()
o_fd.close()

def main():
try:
flag=''
inputfile=''
outputfile=''
opts, args = getopt.getopt(sys.argv[1:], "t:i:o:h",\
["help","type=","infile=","outfile="])
for opt,arg in opts:
if opt in ("-h","--help"):
usage()
elif opt in ("-t","--type"):
flag=arg
elif opt in ("-i","--infile"):
inputfile=arg
elif opt in ("-o","--outfile"):
outputfile=arg
else:
assert False ,"unhandled option"
if flag == '' or inputfile =='' or outputfile=='':
usage()
else :
encode(flag,inputfile,outputfile)
except getopt.GetoptError:
usage()

if __name__ == '__main__':
main()


auto_ssh.sh代码如下:

#!/bin/bash -
#gconftool --set --type=string /apps/gnome-terminal/profiles/Default/encoding GB18030
#export.GB18030
#LANG="zh_CN.UTF-8"
export

config_file=$HOME/sbin/.passwd

ip="$1"
user="$2"
passwd="$3"
resualt=""
gal_flag=""

if [ ! -e "$config_file" ]
then
touch $config_file
fi

help()
{
exit 2
}
chk_config_file()
{
resualt="`grep "\<$ip\>" $config_file`"
if [ "$resualt" = "" ]
then
gal_flag=-1
else
gal_flag=0
fi
}

if [ -z $ip ]
then
help
fi

chk_config_file

login_user="`echo "$resualt"|cut -d " " -f2`"
login_passwd="`echo "$resualt"|cut -d " " -f3`"

if [ "$gal_flag" = "0" ]
then
expect $HOME/sbin/login_ssh $ip $login_user $login_passwd
elif [ "$user" != "" ]
then
expect $HOME/sbin/login_ssh $ip $user $passwd && echo "$ip $user $passwd" >>$config_file
else
help
fi
#gconftool --set --type=string /apps/gnome-terminal/profiles/Default/encoding utf-8
export


login_ssh代码如下:

#!/usr/bin/expect

set timeout 60

if {$argc < 3} {
send "usage:login ip user passwd!\n"
exit
}

set ip    [lindex $argv 0 ]
set user [lindex $argv 1  ]
set passwd [lindex $argv 2  ]

#send "user :$user\n"
#send "pwd :$passwd\n"
#send "ip :$ip\n"

spawn ssh $user@$ip

expect {
"*yes*" {
send "yes\r"
exp_continue
}
"*word*" {
send "$passwd\r"
}

}

interact
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ubuntu ssh expect python