vRO中SSH执行SCP脚本报错,需免密或刷新连接【JS】
问题
我在Red Hat 7虚拟机上基于vRO编写自动化脚本,代码如下:
session = new SSHSession( hostname, username, port ); session.connectWithPassword(password); try { session.executeCommand(command, true); if (session.exitCode !== 0) { //exception handling part... }
当设置command为scp file.txt remote_username@10.10.0.2:/remote/directory时执行失败,错误信息:
- stdout:无内容
- exitCode:1
- stderr:Permission denied, please try again. Permission denied, please try again. Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password). lost connection
- error:"action name" has failed
问题核心:执行SCP时SSH会话因需要输入密码中断,需实现免密执行或处理密码输入的问题。
解决方法
1. 配置SSH密钥对实现免密登录(推荐)
这是最安全可靠的方式,步骤如下:
- 在运行vRO脚本的Red Hat 7主机上生成SSH密钥对:
全程按回车使用默认配置即可,无需设置密码。ssh-keygen -t rsa - 将生成的公钥复制到目标主机
10.10.0.2的remote_username用户目录下:
输入目标用户的密码完成公钥复制。ssh-copy-id remote_username@10.10.0.2 - 验证免密登录:执行
ssh remote_username@10.10.0.2,若无需输入密码即可登录,说明配置成功。 - 之后再运行原vRO脚本,scp命令会自动使用密钥验证,不会触发密码输入请求。
2. 使用sshpass传递密码(临时应急,不推荐生产环境)
如果暂时无法配置密钥对,可借助sshpass工具在命令行传递密码:
- 先在Red Hat 7主机安装sshpass:
yum install sshpass -y - 修改scp命令为:
注意:这种方式会明文暴露密码,存在安全风险,仅适合测试或临时场景。sshpass -p "目标主机remote_username的密码" scp file.txt remote_username@10.10.0.2:/remote/directory
3. 使用vRO内置SCP API(更适配vRO生态)
vRO提供了专门的SCP操作对象,无需通过SSH会话执行命令,底层会自动处理连接和验证:
// 初始化SCP客户端 var scpClient = new SCP("10.10.0.2", "remote_username", "remote_password"); // 上传文件 scpClient.uploadFile("/本地路径/file.txt", "/remote/directory/file.txt"); // 若需下载文件可使用downloadFile方法 // scpClient.downloadFile("/remote/directory/file.txt", "/本地路径/file.txt");
这种方式更符合vRO的自动化规范,避免手动处理命令执行的细节问题。
内容的提问来源于stack exchange,提问作者YagmurOzden
相关产品推荐
相关产品推荐

