[英]How to start interactive ssh terminal from bash script?
I want to start an SSH session from a bash script. 我想从bash脚本启动SSH会话。 After $username and $hostname are read from a file, an interactive SSH session should start like if it was started manually.
从文件中读取$ username和$ hostname之后,交互式SSH会话应该像手动启动一样开始。 The login is done using public key.
使用公共密钥完成登录。
My code: 我的代码:
ssh -t -l $username $hostname
This makes me see the SSH session, but I can't interact with it. 这使我看到了SSH会话,但无法与其进行交互。 How can I solve this?
我该如何解决?
Thanks! 谢谢!
Full script: 完整脚本:
#!/bin/bash
HOSTS_FILE=".mloginconnections"
echo ""
echo " *****************************"
echo " * *"
echo " * MICWAG SSH LOGIN SYSTEM *"
echo " * *"
echo " *****************************"
echo ""
function handleAdd {
echo "Add remote host"
echo ""
echo "Enter connection alias:"
read aliasname
echo "Enter hostname:"
read hostname
echo "Enter username:"
read username
if [ ! -f $HOSTS_FILE ]
then
touch $HOSTS_FILE
fi
echo "$aliasname:$hostname:$username" > $HOSTS_FILE
}
function handleConnect {
if [ $# -ne 1 ]
then
echo "Usage:"
echo "connect [serveralias]"
else
echo "Try to connect to server $1"
cat $HOSTS_FILE | while read line
do
IFS=':' read -ra conn <<< $line
aliasname=${conn[0]}
hostname=${conn[1]}
username=${conn[2]}
if [ "$aliasname" == "$1" ] || [ "$hostname" == "$1" ]
then
echo "Found host: $username@$hostname"
ssh -tt -l $username $hostname
fi
done
fi
}
function handleCommand {
echo "Enter command:"
read command
case $command in
add)
handleAdd
;;
exit)
exit
;;
*)
handleConnect $command
;;
esac
echo ""
}
while [ 1 ]
do
handleCommand
done
The problem is that you give ssh
input from your cat $HOSTS_FILE
command instead of from your keyboard. 问题是您从
cat $HOSTS_FILE
命令而不是从键盘提供ssh
输入。 That's why you can't interact with it. 这就是为什么您无法与其互动。
The easiest, ugliest fix is to redirect from the current tty: 最简单,最丑陋的修复是从当前tty重定向:
ssh -t -l $username $hostname < /dev/tty
You need to provide to -t
switches as described in manual page for ssh
: 您需要提供
ssh
手册页中所述的-t
开关:
ssh -tt -l $username $hostname
Description from manual page: 手册页中的描述:
Multiple -t options force tty allocation, even if ssh has no local tty.
即使ssh没有本地tty,多个-t选项也会强制tty分配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.