ssh一键登录脚本

linux,python 2018-08-28 902

一键登录脚本

mac一键登录脚本前置依赖

  • expect
  • python
  • crontab

依照现在的登录条件,需要在登录跳板机时输入账号密码还有google code。我现在的办法是通过crontab生成google code,并将code存贮的临时文件中,然后登录脚本在去临时文件中获取code,实现登录

#### 1.获取google code
import hmac, base64, struct, hashlib, time

def calGoogleCode(secretKey):
    input = int(time.time())//30
    key = base64.b32decode(secretKey)
    msg = struct.pack(">Q", input)
    googleCode = hmac.new(key, msg, hashlib.sha1).digest()
    o = ord(googleCode[19]) & 15
    googleCode = str((struct.unpack(">I", googleCode[o:o+4])[0] & 0x7fffffff) % 1000000)
    if len(googleCode) == 5:
        googleCode = '0' + googleCode
    return googleCode

code = calGoogleCode('your code')

file = "/tmp/code.txt"
with open(file,"w") as f:
    f.write(code)

:这里我将生成的code存储在了/tmp/code.txt

2.crontab配置

* * * * * python /Users/leisun/authy.py
* * * * * (sleep 30; python /Users/leisun/authy.py)

:因为crontab最小执行时间是1分钟,而code是30秒变化一次,所以添加两个定时

3.登录脚本

使用前先安装下export

brew install expect

请安要求填写你的信息

#!/usr/bin/expect

set fp [open /tmp/code.txt r]
set code [read -nonewline $fp]
close $fp
set pwd "it is your relay pwd"
send ${code}\n;
spawn ssh your name@relay.afpai.com
expect "*code*"
send ${code}\n;
expect "*assword*"
send ${pwd}
send \n;
expect "*relay*"
send "ssh homework@your Ip\r"
expect "*assword*"
send "it is manchine pwd\n"
interact

如何保持ssh连接不断

请阅读 [Linux使用ssh超时断开连接的真正原因] (http://bluebiu.com/blog/linux-ssh-session-alive.html) 作者 biubiu


本文由 创作,采用 知识共享署名 3.0,可自由转载、引用,但需署名作者且注明文章出处。

还不快抢沙发

添加新评论