大网数据广告活动
服务器运维问答

SSH ask password once, reuse password until timeout finishes

· 52CE 我爱测

How can I solve this problem? I have a bash script (under Ubuntu Server), doing several SSH connections, executes some remote transfers, like rsync multiple times. My problem is, that I would like to avoid entering password multi…

问题原文

原帖链接 · klor · CC BY-SA 3.0

How can I solve this problem? I have a bash script (under Ubuntu Server), doing several SSH connections, executes some remote transfers, like rsync multiple times.

My problem is, that I would like to avoid entering password multiple times. But I don't want to use SSH public key exchange, because if anybody has the key, will be able to connect the remote computer.

I would like the following:

  • SSH should ask password when I start the bash script
  • reuse password, so don't ask password again until timeout
  • when timeout is over, ask password again.

Something similar, how sudo is working, just with ssh.

Any idea how to solve this?

EDIT1:

I found a new SSH feature named ssh multiplexing. Maybe using this I can reach the goal I want.

https://unix.stackexchange.com/questions/50508/reusing-ssh-session-for-repeated-rsync-commands

Would this work?

社区高分解答

原帖链接 · James Sneeringer · CC BY-SA 4.0

It's not what you want to hear, but this is what key-based authentication is for. So long as you put a passphrase on your private key, it's no less secure than password authentication.

You can use ssh-agent to avoid needing to enter the passphrase every time, and the -t option to ssh-agent will give you the timeout behavior you're after.

# start a shell under ssh-agent with a 5-minute timeout for keys loaded with ssh-add
ssh-agent -t 300 /bin/bash

# add your key(s) to the agent; ssh-add will prompt for passphrase, if one is set
ssh-add

# do some stuff
ssh remote.server cat /some/file
rsync file1 file2 [email omitted]:/some/directory

# after 300 seconds, timeout reached, run ssh-add again to re-add your keys
ssh-add

Your script will need some logic to determine when the timeout occurs. One way would be to run ssh and rsync with -o BatchMode=yes, which will prevent interactive authentication methods, so if the key is no longer usable, ssh will exit instead of prompting for a password. You can use the exit code to determine if you need to run ssh-add again; $? should be set to 255 in this case.

You'll still need to work out how to feed the passphrase to ssh-add, because it doesn't provide a way to accept it programmatically. Unless your script will prompt you to enter it by hand, you'll probably need to use expect for that part, and that will mean hard-coding the passphrase somewhere.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2017-03-31)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0 / CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。