linux - 期望和 Bash 脚本

标签 linux bash shell except

我正在尝试执行一个带有循环的 expect 脚本,该循环尝试在 ssh 中连接并查看是否可行(良好的密码且可访问)。我试图将结果放入一个变量中,但只记录了 stdout 的末尾,而不是所有的 stdout。我怎么办?

result=$(
(/usr/bin/expect << EOF
    spawn ssh $username@$ip -o StrictHostKeyChecking=no
    set timeout 2
    expect ":"
    send -- "$password\r"
    expect ">"
    send -- "show clock\r"
    expect ">"
EOF
) 2>&1)

谢谢。

最佳答案

如果您尝试使用 ssh 自动向另一台服务器发送命令:

  • 生成 ssh key ,而不是使用密码:

    ssh-keygen -t rsa -b 2048
    
  • 复制到服务器:

    ssh-copy-id id@server
    

现在您无需担心密码问题。 ssh key 用作密码,通常 更安全。有关 ssh key 的更多信息,请参阅这些(SSH login without passwordWhy is using SSH key more secure than using passwords?)。

然后你可以只使用这个命令 - 不需要 expect,因为你不会被要求输入密码。它将使用您的 ssh key 。我的位于 ~/.ssh/id_rsa。所以:

ssh id@server -i ~/.ssh/id_rsa "show clock;"
  • -i 代表身份文件,即您的ssh key 文件。

将向 SSH 服务器发送命令。

现在:

ssh-keygen -t rsa -b 2048
ssh-copy-id id@server
ssh id@server -i ~/.ssh/id_rsa "show clock;"

三个命令,你就搞定了!

关于linux - 期望和 Bash 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38792655/

相关文章:

linux - ./而不是/在 crontab 中

c - 两次向 Linux 内核双链表添加元素

linux - "mvn -version"不返回版本

regex - 使用 sed 删除两个空格字符之间的字符串

linux - 为具有管道的 watch 命令添加别名

php - 如何在没有 php 脚本中断的情况下执行外部程序

linux - 在文件中使用 sed 替换复杂行

c - 这个泛型函数是如何使用的

c - BSD(Mac OS X 和 OpenBSD)和 Linux (Ubuntu) 之间的套接字行为不同

bash - 仅使用 md5sum 获取哈希值(不带文件名)