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

#各个脚本的功能介绍
#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


转载于:https://my.oschina.net/u/1035860/blog/215821

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值