如何在Makefile或C语言system()调用中输入密码?
解决scp自动输入密码问题:Makefile与C代码实现方案
最优方案:SSH密钥认证(无密码登录)
这是最安全、长期维护成本最低的方案,彻底跳过密码输入环节,步骤如下:
- 生成本地SSH密钥对:
ssh-keygen -t ed25519(全程回车,无需设置密钥保护密码) - 将公钥上传至远程服务器:
ssh-copy-id user@remote_host(仅首次执行需手动输入服务器密码) - 验证有效性:直接执行
ssh user@remote_host或scp local_file user@remote_host:/path/,此时无需输入任何密码
在Makefile中使用
直接编写部署规则即可,无需额外处理密码:
deploy: scp ./your_executable user@remote_host:/target/deploy/path/
在C代码system()调用中使用
直接拼接scp命令字符串,无需密码相关处理:
#include <stdlib.h> int main() { system("scp ./local_upload_file user@remote_host:/target/upload/path/"); return 0; }
应急方案:明文密码传递(不推荐)
如果临时无法配置SSH密钥,可通过管道传递密码,但此方式存在严重安全风险(密码会明文暴露在代码、Makefile或系统进程列表中),仅适合临时测试场景:
Makefile实现
deploy: echo "your_server_password" | scp -o StrictHostKeyChecking=no ./your_executable user@remote_host:/target/path/
C代码system()调用实现
#include <stdlib.h> int main() { system("echo \"your_server_password\" | scp -o StrictHostKeyChecking=no ./local_file user@remote_host:/target/path/"); return 0; }
注意:
-o StrictHostKeyChecking=no用于跳过首次连接的主机密钥确认,同样存在安全隐患,仅临时使用。
内容的提问来源于stack exchange,提问作者ZeroKelvin
相关产品推荐
相关产品推荐

