您可以在cron会话中建立ssh连接。您需要设置一个公共密钥身份验证以具有无密码访问权限。为此,您需要安装PubkeyAuthentication yes
在每个远程服务器的中sshd_config
。
您可以创建带有或不带有密码短语的私钥/公钥对。如果使用密码短语(建议),则还需要启动ssh-agent。如果没有密码短语,则只需将参数添加-i your_identity_file
到ssh
命令行即可。ssh
将$HOME/.ssh/id_rsa
默认使用。
我通过使用带有密码短语的密钥对来复制您的示例。这是我的方法。
1)用密码创建密钥对。将私钥另存为~/.ssh/id_rsa_test
,默认情况下应具有正确的权限。我们可以输入一个不使用的空密码。
john@coffee:~$ ssh-keygen -N "somephrase" -f .ssh/id_rsa_test
Generating public/private rsa key pair.
Your identification has been saved in .ssh/id_rsa_test.
Your public key has been saved in .ssh/id_rsa_test.pub.
[snip]
2)将公钥发送到服务器,并对所有服务器执行相同的操作。记住,他们需要PubkeyAuthentication
启用。
john@coffee:~$ ssh-copy-id -i .ssh/id_rsa_test server1
The authenticity of host 'server1 (11.22.33.1)' can't be established.
RSA key fingerprint is 79:e8:0d:f5:a3:33:1c:ae:f5:24:55:86:82:31:b2:76.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'server1,11.22.33.1' (RSA) to the list of known hosts.
john@server1's password:
Now try logging into the machine, with "ssh 'server1'", and check in:
.ssh/authorized_keys
to make sure we haven't added extra keys that you weren't expecting.
3)使用ssh-agent作为服务运行-s
。如果您注销,这不会杀死它。它的输出是一个有效的shell脚本,它设置了环境,以便ssh客户端知道如何连接到它。我们将其保存到文件中(只需要第一行)。
john@coffee:~$ ssh-agent -s | head -n 1 > ssh-agent.cf
john@coffee:~$ cat ssh-agent.cf
SSH_AUTH_SOCK=/tmp/ssh-VhyKL22691/agent.22691; export SSH_AUTH_SOCK;
4)将以上内容加载到我们当前的环境中,以便我们可以ssh-add
将私钥添加到中ssh-agent
。上方的密码。
john@coffee:~$ source ssh-agent.cf
john@coffee:~$ ssh-add .ssh/id_rsa_test
Enter passphrase for .ssh/id_rsa_test:
Identity added: .ssh/id_rsa_test (.ssh/id_rsa_test)
5)确认已添加。
john@coffee:~$ ssh-add -l
2048 96:58:94:67:da:67:c0:5f:b9:0c:40:9b:52:62:55:6a .ssh/id_rsa_test (RSA)
6)我使用的脚本比您的脚本稍作修改。请注意,我没有将ssh命令括在括号中,也没有使用反引号$()
,这是命令替换的更好选择(这是bash
兼容的,您没有提到您使用的是哪个shell)。我使用了与您完全相同的ssh命令。
john@coffee:~$ cat foo.sh
#!/bin/bash
source /home/john/ssh-agent.cf
for server in server1 server2; do
usr=$(ssh -t -t -o ConnectTimeout=60 $server finger | tail -1 | awk '{print $1}')
date=$(ssh -o ConnectTimeout=60 $server date)
echo "$server - $date - $usr" >> /home/john/foo.log
done
7)我的crontab(请注意,我sh
实际上是bash
)
john@coffee:~$ crontab -l
# m h dom mon dow command
*/1 * * * * sh /home/john/foo.sh
8)输出
john@coffee:~$ tail -n 4 foo.log
server1 - Wed Mar 23 14:12:03 EET 2011 - john
server2 - Wed Mar 23 14:12:04 EET 2011 - john
server1 - Wed Mar 23 14:13:03 EET 2011 - john
server2 - Wed Mar 23 14:13:04 EET 2011 - john
使用密码短语的唯一问题是,您需要至少手动输入一次。因此,以上内容在重启后将无法自动运行。