好吧,这是我从server.txt列表ssh到服务器时的部分代码。
while read server <&3; do #read server names into the while loop
serverName=$(uname -n)
if [[ ! $server =~ [^[:space:]] ]] ; then #empty line exception
continue
fi
echo server on list = "$server"
echo server signed on = "$serverName"
if [ $serverName == $server ] ; then #makes sure a server doesnt try to ssh to itself
continue
fi
echo "Connecting to - $server"
ssh "$server" #SSH login
echo Connected to "$serverName"
exec < filelist.txt
while read updatedfile oldfile; do
# echo updatedfile = $updatedfile #use for troubleshooting
# echo oldfile = $oldfile #use for troubleshooting
if [[ ! $updatedfile =~ [^[:space:]] ]] ; then #empty line exception
continue # empty line exception
fi
if [[ ! $oldfile =~ [^[:space:]] ]] ; then #empty line exception
continue # empty line exception
fi
echo Comparing $updatedfile with $oldfile
if diff "$updatedfile" "$oldfile" >/dev/null ; then
echo The files compared are the same. No changes were made.
else
echo The files compared are different.
cp -f -v $oldfile /infanass/dev/admin/backup/`uname -n`_${oldfile##*/}_$(date +%F-%T)
cp -f -v $updatedfile $oldfile
fi
done
done 3</infanass/dev/admin/servers.txt
我一直收到这个错误,ssh实际上并没有在服务器上连接和执行代码,它假设是ssh打开的
Pseudo-terminal will not be allocated because stdin is not a terminal
我觉得上面那个家伙说的一切都错了。
期待?
很简单:
ssh -i ~/.ssh/bobskey bob@10.10.10.10 << EOF
echo I am creating a file called Apples in the /tmp folder
touch /tmp/apples
exit
EOF
2个"EOF"之间的所有内容都将在远程服务器中运行。
标签必须相同。如果您决定将"EOF"替换为"WayneGretzky",您也必须更改第二个EOF。
您似乎认为,当您运行ssh
连接到服务器时,文件中的其余命令将传递给在ssh
中运行的远程shell。它们不是;相反,一旦ssh
终止并将控制权返回给它,它们将由本地shell处理
要通过ssh
运行远程命令,可以做以下几件事:
- 将要执行的命令写入文件。使用
scp
将文件复制到远程服务器,并使用ssh user@remote command
执行 - 学习一点TCL并使用
expect
-
在heredoc中编写命令,但要小心变量替换:替换发生在客户端,而不是服务器上。例如,这将输出您的本地主目录,而不是远程:
ssh remote <<EOF echo $HOME EOF
要使它打印远程主目录,您必须使用
echo $HOME
。
此外,请记住,如果要在远程端读取filelist.txt
等数据文件,则必须显式复制它们。