linux脚本使用scp自动传输,使用Shell脚本自动传输SCP文件

我的unix系统上的目录中有n个文件。 有没有一种方法可以编写Shellscript,该脚本将通过scp将所有这些文件传输到指定的远程系统。 我将在脚本中指定密码,这样就不必为每个文件输入密码。

您能告诉我在rsync中在shell脚本中使用密码是否有效,或者您是否尝试过密码? 谢谢。

与其在shell脚本中对密码进行硬编码,不如使用SSH密钥,它更容易且安全。

$ scp -i ~/.ssh/id_rsa devops@myserver.org:/path/to/bin/*.derp .

假设您的私钥位于~/.ssh/id_rsa

生成公钥/私钥对:

$ ssh-keygen -t rsa

上面将生成2个文件,~/.ssh/id_rsa(私钥)和~/.ssh/id_rsa.pub(公钥)

设置SSH密钥以使用(一次任务):

复制~/.ssh/id_rsa.pub的内容并粘贴到myserver.org服务器中的新行~devops/.ssh/authorized_keys中。如果~devops/.ssh/authorized_keys不存在,请随时创建它。

此处提供了清晰的操作指南。

即使按照这些说明进行操作,仍然会提示我输入密码...我是否还缺少其他标准?

@ScottScooterWeidenkopf可能有些错误,例如.ssh目录或authenticated_keys文件可能没有正确的权限(700)。

@PradeepPati我想出了我的问题。没错,问题出在权限。在您提供的链接中,作者提到了一些权限更改。我做了这些更改,现在一切正常。

#!/usr/bin/expect -f

# connect via scp

spawn scp"user@example.com:/home/santhosh/file.dmp" /u01/dumps/file.dmp

#######################

expect {

-re".*es.*o.*" {

exp_send"yes

"

exp_continue

}

-re".*sword.*" {

exp_send"PASSWORD

"

}

}

interact

http://blogs.oracle.com/SanthoshK/entry/automate_linux_scp_command

Windows用户注意:MSYS2中打包的expect将与整个输出匹配,因此第一个规则将始终匹配。如果交换两个规则的顺序,则会得到所需的行为。

你为什么不试试这个?

password="your password"

username="username"

Ip=""

sshpass -p"$password" scp //final.txt $username@$Ip:/root/

很好的替代#!/ usr / bin / expect -f

您也可以使用rsync。对于多个文件,它似乎比scp IMHO更好。

rsync -avzh /path/to/dir/ user@remote:/path/to/remote/dir/

更新资料

您可以通过添加'-e'开关通过ssh使用rsync:

rsync -avzh -e ssh /path/do/dir/ user@remote:/path/to/remote/dir/

关于scpist的好处是它使用安全通道。 rsync没有。

您可以强制rsync使用ssh:rsync -avz -e ssh remoteuser @ remotehost:/ remote / dir / this / dir /

@flokra。谢谢,我正好在添加该更新的过程中,并且分心了。

这仍将调用交互式密码提示。我相信OP想要一个完全自动化的解决方案

@Tom SCP -r将完美工作

@Dimitri scp -r递归复制文件。它与在脚本中存储密码并通过bash脚本将密码传递给scp调用无关!我真的不明白你的评论。

#!/usr/bin/expect -f

spawn scp -r BASE.zip abhishek@192.168.1.115:/tmp

expect"password:"

send"wifinetworks

"

expect"*

"

expect"

"

可以预期用于rsync吗?我正在尝试做某事,但是我的RSA密钥方法不起作用。它一直问我远程计算机的密码。

那通配符或多个文件呢?

scp file1 file2 more-files* user@remote:/some/dir/

rsync是一个程序,其行为与rcp大致相同,但是具有更多的选项和用途

rsync远程更新协议可以大大加快目标文件传输过程中的文件传输速度

更新。

rsync远程更新协议允许rsync仅传输两组文件之间的差异

使用技术中描述的高效校验和搜索算法在整个网络连接中

报告随附此软件包。

将文件夹从一个位置复制到另一位置

#!/usr/bin/expect -f

spawn rsync -a -e ssh username@192.168.1.123:/cool/cool1/* /tmp/cool/

expect"password:"

send"cool

"

expect"*

"

expect"

"

如果可以在每次运行脚本时都输入一次密码,则可以使用SSH主连接轻松进行。

#!/usr/bin/env bash

USER_AT_HOST="user@host"  # use"$1@$2" here if you like

SSHSOCKET=~/".ssh/$USER_AT_HOST"

# This is the only time you have to enter the password:

# Open master connection:

ssh -M -f -N -o ControlPath="$SSHSOCKET""$USER_AT_HOST"

# These do not prompt for your password:

scp -o ControlPath="$SSHSOCKET" file1.xy"$USER_AT_HOST":remotefile1.xy

scp -o ControlPath="$SSHSOCKET" file2.xy"$USER_AT_HOST":remotefile2.xy

# You can also use the flag for normal ssh:

ssh -o ControlPath="$SSHSOCKET""$USER_AT_HOST""echo hello"

ssh -o ControlPath="$SSHSOCKET""$USER_AT_HOST""echo world"

# Close master connection:

ssh -S"$SSHSOCKET" -O exit"$USER_AT_HOST"

这是带有.pem密钥文件的SCP的bash代码。

只需将其保存到script.sh文件,然后使用" sh script.sh"运行

请享用

#!/bin/bash

#Error function

function die(){

echo"$1"

exit 1

}

Host=ec2-53-298-45-63.us-west-1.compute.amazonaws.com

User=ubuntu

#Directory at sent destination

SendDirectory=scp

#File to send at host

FileName=filetosend.txt

#Key file

Key=MyKeyFile.pem

echo"Aperture in Process...";

#The code that will send your file scp

scp -i $Key $FileName $User@$Host:$SendDirectory || \

die"@@@@@@@Houston we have problem"

echo"########Aperture Complete#########";

您只能使用ssh公钥/私钥来做到这一点。或者使用可以在其中设置密码的腻子。 scp不支持在命令行中提供密码。

您可以在此处找到有关公钥/私钥的说明:

http://www.softpanorama.org/Net/Application_layer/SSH/scp.shtml

这将起作用:

#!/usr/bin/expect -f

spawn scp -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no file1 file2 file3 user@host:/path/

expect"password:"

send"xyz123

"

expect"*

"

expect"

"

interact

试试lftp

lftp -u $user,$pass sftp://$host << --EOF--

cd $directory

put $srcfile

quit

--EOF--

可以像传统的UNIX cp一样使用命令scp。所以,如果你这样做:

scp -r myDirectory/ mylogin@host:TargetDirectory

将工作

这似乎没有解决密码问题。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
java远程访问linux服务器操作 远程执行shll脚本或者命令、上传下载文件 package com.szkingdom.kfit.bank.ccbDirectShortcut.helper; import ch.ethz.ssh2.Connection; import ch.ethz.ssh2.SCPClient; import ch.ethz.ssh2.Session; import ch.ethz.ssh2.StreamGobbler; import common.Logger; import org.apache.commons.lang.StringUtils; import java.io.*; import java.util.logging.Level; /** * SCP远程访问Linux服务器读取文件 * User: boyer * Date: 17-12-7 * Time: 下午3:22 * To change this template use File | Settings | File Templates. */ public class ScpClient { //字符编码默认是utf-8 private static String DEFAULTCHART="UTF-8"; protected static org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(ScpClient.class); static private ScpClient instance; private Connection conn; static synchronized public ScpClient getInstance(String IP, int port, String username, String passward) { if (instance == null) { instance = new ScpClient(IP, port, username, passward); } return instance; } public ScpClient(String IP, int port, String username, String passward) { this.ip = IP; this.port = port; this.username = username; this.password = passward; } private String ip; private int port; private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } /** * 远程登录linux的主机 * @author Ickes * @since V0.1 * @return * 登录成功返回true,否则返回false */ public Boolean login(){ boolean flg=false; try { conn = new Connection(ip); conn.connect();//连接 flg=conn.authenticateWithPassword(username, password);//认证 } catch (IOException e) { e.printStackTrace(); } return flg; } /** * 下载文件 * @param remoteFile 远程文件地址 * @param localTargetDirectory 本地目录地址 */ public void getFile(String remoteFile, String localTargetDirectory) { try { if(login()){ SCPClient client = new SCPClient(conn); client.get(remoteFile, localTargetDirectory); conn.close(); } } catch (IOException ex) { log.error(ex); } } /** * 上传文件 * @param localFile 本地目录地址 * @param remoteTargetDirectory 远程目录地址 */ public void putFile(String localFile, String remoteTargetDirectory) { try { if(login()){ SCPClient client = new SCPClient(conn); client.put(localFile, remoteTargetDirectory); conn.close(); } } catch (IOException ex) { log.error(ex); } } /** * 上传文件 * @param localFile 本地目录地址 * @param remoteFileName 重命名 * @param remoteTargetDirectory 远程目录地址 * @param mode 默认0600权限 rw 读写 */ public void putFile(String localFile, String remoteFileName,String remoteTargetDirectory,String mode) { try { if(login()){ SCPClient client = new SCPClient(conn); if((mode == null) || (mode.length() == 0)){ mode = "0600"; } client.put(localFile, remoteFileName, remoteTargetDirectory, mode); //重命名 ch.ethz.ssh2.Session sess = conn.openSession(); String tmpPathName = remoteTargetDirectory +File.separator+ remoteFileName; String newPathName = tmpPathName.substring(0, tmpPathName.lastIndexOf(".")); sess.execCommand("mv " + remoteFileName + " " + newPathName);//重命名回来 conn.close(); } } catch (IOException ex) { log.error(ex); } } public static byte[] getBytes(String filePath) { byte[] buffer = null; try { File file = new File(filePath); FileInputStream fis = new FileInputStream(file); ByteArrayOutputStream byteArray = new ByteArrayOutputStream(1024*1024); byte[] b = new byte[1024*1024]; int i; while ((i = fis.read(b)) != -1) { byteArray.write(b, 0, i); } fis.close(); byteArray.close(); buffer = byteArray.toByteArray(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return buffer; } /** * @author Ickes * 远程执行shll脚本或者命令 * @param cmd * 即将执行的命令 * @return * 命令执行完后返回的结果值 * @since V0.1 */ public String execute(String cmd){ String result=""; try { if(login()){ Session session= conn.openSession();//打开一个会话 session.execCommand(cmd);//执行命令 result=processStdout(session.getStdout(),DEFAULTCHART); //如果为得到标准输出为空,说明脚本执行出错了 if(StringUtils.isBlank(result)){ result=processStdout(session.getStderr(),DEFAULTCHART); } conn.close(); session.close(); } } catch (IOException e) { e.printStackTrace(); } return result; } /** * @author Ickes * 远程执行shll脚本或者命令 * @param cmd * 即将执行的命令 * @return * 命令执行成功后返回的结果值,如果命令执行失败,返回空字符串,不是null * @since V0.1 */ public String executeSuccess(String cmd){ String result=""; try { if(login()){ Session session= conn.openSession();//打开一个会话 session.execCommand(cmd);//执行命令 result=processStdout(session.getStdout(),DEFAULTCHART); conn.close(); session.close(); } } catch (IOException e) { e.printStackTrace(); } return result; } /** * 解析脚本执行返回的结果集 * @author Ickes * @param in 输入流对象 * @param charset 编码 * @since V0.1 * @return * 以纯文本的格式返回 */ private String processStdout(InputStream in, String charset){ InputStream stdout = new StreamGobbler(in); StringBuffer buffer = new StringBuffer();; try { BufferedReader br = new BufferedReader(new InputStreamReader(stdout,charset)); String line=null; while((line=br.readLine()) != null){ buffer.append(line+"\n"); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return buffer.toString(); } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值