在 bash 中使用密码的安全方式并期待

Secure way to use password in bash and expect

bash 如何使用密码安全地调用 expect 脚本?

我有两个脚本:一个由用户直接执行的bash脚本,以及一个由bash脚本调用并使用登录到远程主机的expect脚本bash 脚本中提供的密码。

bash 脚本 (main.sh)

#!/bin/bash

read -p "User: " user
read -s -p "Password: " password

./login.expect "$user" "$password"

期待脚本 (login.expect)

#!/usr/bin/expect --

set user [lindex $argv 0]
set password [lindex $argv 1]
set host 192.168.1.15

spawn ssh $user@$host
expect -re ".*ssword.*" { send "$password\n" }    # Send password
expect -re ":~\$" { send "ls\n" }               # Do stuff
expect -re ":~\$" { send "exit\n" }             # exit

此设置的至少一个问题是有人可以通过使用 "ps -ef" 观察进程来学习密码,因为密码是在命令行上提供的。

这些脚本比我的实际脚本简化了很多,因为我只是想了解这部分是否可以通过某种方式安全地完成。我的实际用例非常复杂,需要 bash 和 expect 脚本分开,所以我不能只将 expect 嵌入到 bash 中,也不能从 expect 脚本中请求密码。同样不幸的是,ssh 密钥不是无密码登录的选项。我可以重组 expect 脚本以通过命令行选项以外的其他方式获取密码,但我不确定什么是好的替代方案。

我现在最好的选择是在 bash 中加密密码,将加密后的密码作为参数传递给 expect 脚本,并让 expect 解密密码(我没有确切的机制)为此)。

有没有更好的方法?

您可以在某种程度上安全地通过环境传递密码,因为它只能由同一用户和 root 读取。在 shell export passwordexpect 脚本中

set password $env(password)

从文件读取密码

set passfile [open "~/.sshpass" r]
gets $passfile userpass
close $passfile

chmod 700 ~/.sshpass