当前位置:   article > 正文

Linux/MacOS下脚本登录远程服务器_linux 使用脚本连接到另一台机器

linux 使用脚本连接到另一台机器

本文最先发布于我的个人博客,CSDN为同步发布,如有需要,请访问 腿短快跑的个人博客 获取更多内容

起因

最近在折腾Ubuntu系统,有时候需要连接远程服务器,使用 ssh 命令连接较为复杂,需要记住每台机器的 ip 和 密码,当然 Ubuntu(linux) 下也有类似于 xshell 一样的管理工具,例如:finalShell,但是在命令行下没有方便管理的工具,因此打算自己实现一个简单的,此方案同样适用于MacOS

选型

自动交互:
Linux环境下有 expect 命令允许通过自动接收命令输出并根据不同输出自动输入对应内容,满足我们自动输入密码、yes等命令的需要

操作交互:

  • shell读取文件并输入
  • python读取文件并输出

shell操作json较为复杂,如果使用普通空格等来作为分隔符,shell也需要复杂的切割逻辑,且 Linux 系统一般原生支持python,python可以很方便的操作文件并输出,因此选择python来交互

实现

安装软件

# 更新软件包
apt-get update
apt-get upgrade
# 安装expect
apt-get install expect
# 安装python3
apt-get install python3
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

服务器配置文件

# 创建目录
mkdir  /usr/local/login
# 创建文件
touch /usr/local/login/server.json
  • 1
  • 2
  • 3
  • 4

/usr/local/login/server.json

[
  {
    "host": "服务器IP或域名",
    "user": "服务器账号",
    "password": "服务器密码",
    "remark": "服务器说明"
  }
]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

expect登录脚本

touch /usr/local/login/ssh-except.exp
  • 1

/usr/local/login/ssh-except.exp

#!/bin/expect
set ipaddr [lindex $argv 0]
set user [lindex $argv 1]
set passwd [lindex $argv 2]
set timeout 30
spawn ssh $user@$ipaddr
expect {
    "yes" {send "yes\r";exp_continue}
    "password" {send "$passwd\r"}
}
expect eof
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

用户交互脚本

# 创建登录脚本
touch /usr/local/bin/login
# 设置脚本可执行权限
chmod +x /usr/local/bin/login
  • 1
  • 2
  • 3
  • 4

/usr/local/bin/login

#!/usr/bin/python3
import json
import os

server_list=[]
with open("/usr/local/login/server.json", "r") as file:
    server_list = json.load(file)
# 打印主界面
while True:
    print("\n\n=====================================")
    print("序号\t主机\t\t说明")
    i = 1
    print("0\t退出")
    for server in server_list:
        print(str(i)+"\t"+server['host']+"\t"+server['remark'])
        i=i+1
    print("=====================================")
    index=input("请选择服务器编号:")
    try:
        server_index=int(index)
        if server_index == 0:
            break
        if server_index > len(server_list) or server_index < 0:
            print("编号不合法")
            continue
        server = server_list[server_index-1]
        os.system("expect /usr/local/login/ssh-except.exp " + server['host'] + " "+ server['user'] +" "+ server['password'] +" ")
    except Exception as e:
        print("编号不合法")
        continue
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

测试

img

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/866325?site
推荐阅读
相关标签
  

闽ICP备14008679号