博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
利用shell + python + expect实现类似xshell功能(测试环境:ubuntu)
阅读量:6936 次
发布时间:2019-06-27

本文共 9366 字,大约阅读时间需要 31 分钟。

hot3.png

#各个脚本的功能介绍#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-01trap _exit 2config=$HOME/sbin/.passwdkey_file=$HOME/sbin/.key.datmk_pass=$HOME/sbin/mk_key_filecclear_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_guiresult=$?if [ $result -eq 1 ]then    main_guielse    mainfi_exit

mk_key_filec 是mk_key_file脚本编译成的编译代码如下:#!/usr/bin/pythonimport py_compileimport syspy_compile.compile(sys.argv[1])mk_key_file代码如下:#!/usr/bin/python#-*- ecoding= utf-8 -*-import osimport sysimport base64import getoptdef 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 Falsedef 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_filenantian@nantian-ThinkPad-Edge-E430:~/sbin$ cat mk_key_file#!/usr/bin/python#-*- ecoding= utf-8 -*-import osimport sysimport base64import getoptdef 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 Falsedef 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"exportconfig_file=$HOME/sbin/.passwdip="$1"user="$2"passwd="$3"resualt=""gal_flag=""if [ ! -e "$config_file" ]then    touch $config_filefihelp(){    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    helpfichk_config_filelogin_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_fileelse    helpfi#gconftool --set --type=string /apps/gnome-terminal/profiles/Default/encoding utf-8export

login_ssh代码如下:#!/usr/bin/expectset timeout 60if {$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

你可能感兴趣的文章
【转】java线程系列---Runnable和Thread的区别
查看>>
微信公众号开发之微信JSSDK
查看>>
函数式编程(小练习)
查看>>
Git 创建两个“本地分支”协同工作
查看>>
she
查看>>
JS脚本调试
查看>>
病毒实验二
查看>>
IOS开发中的变量、方法、属性
查看>>
IT风险管理专家CISRE认证
查看>>
yii redirect
查看>>
uva-10954-贪心
查看>>
wxPython笔记
查看>>
使用 邮箱配置 激活码 用于 用户注册激活
查看>>
Recover Binary Search Tree
查看>>
Linux之因BASH造成的键盘错误和环境问题
查看>>
RBAC权限设计实例(转)
查看>>
JavaScript求当月天数
查看>>
一个典型的后台软件系统的设计复盘——(二)如何id一个事物
查看>>
springboot 详细配置2
查看>>
这么小的key-val数据库居然也支持事务——与短跑名将同名的数据库Bolt
查看>>