---
title: "ant使用ssh和linux交互 如：上传文件"
author: "iammonster"
date: "2010-08-19T12:50:38Z"
tags: []
categories: ["研发管理"]
slug: "ant-ssh-linux"
draft: false
lastmod: "2010-08-19T12:50:38Z"
id: 741001
url: "https://jiajun.iteye.com/blog/741001"
---

**背景：**

ant生成jar包之后，每次都要往目标机器上拷贝部署，真是难受。

 

本机又是Windows ，运行机器是linux，如何办？来个共享？安装samba？

 

高人指点，采用ftp，要去配置个ftp还是不爽的事情，想既然ant支持ftp肯定考虑支持sftp等关于ssh的功能，一查发现，果然还是支持的。兴奋！

 

**一、寻找资源文件**

看ant的文档：

http://ant.apache.org/manual/Tasks/scp.html

 

在依赖的jar包列表 http://ant.apache.org/manual/install.html#librarydependencies 中找到

jsch.jar **0.1.42 or later**

 

进入http://www.jcraft.com/jsch/index.html 找到下载地址：http://sourceforge.net/projects/jsch/files/jsch/jsch-0.1.43.jar/download

 

源码地址：http://sourceforge.net/projects/jsch/files/jsch/jsch-0.1.43.zip/download

 

**二、测试可行性**

下载后，放入自己的ant下的lib文件夹下，如果是eclipse需要加入运行环境window-&gt;preferences-&gt;ant-&gt;runtime-&gt;classpath中加入jsch-0.1.43.jar

 

例子，可以采用http://ant.apache.org/manual/Tasks/scp.html里面的examples，还挺全的，拷贝单个文件，拷贝文件夹，设置密码，设置私钥等

**scp**

下面亲自测试几个：

```
    
    <target name="scp-file">
        <scp file="jar/fetch.jar" todir="uu:123@192.168.0.175:/home/uu/fetch" />
    </target>
   
    <target name="scp-folder">
            <scp todir="uu:123@192.168.0.175:/home/uu/fetch" >
                 <fileset dir="jar"/>
            </scp>
    </target>

```

com.jcraft.jsch.JSchException: reject HostKey: 192.168.0.175

 

会有以上的异常，奇怪的官方文档不说。要求你所连接的host必须存在于你的knownhosts文件中，并且 这个文件也必须是存在的，否则会出现上面的异常。

 

解决方法：

 

```
    <target name="scp-file">
        <scp file="jar/fetch.jar" todir="uu:123@192.168.0.175:/home/uu/fetch" trust="true"
/>
    </target>
   
    <target name="scp-folder">
            <scp todir="uu:123@192.168.0.175:/home/uu/fetch" trust="true"
>
                 <fileset dir="jar"/>
            </scp>
    </target>
```

 

**sshexec**

再测试一下诱惑人的可执行shell功能，文档地址;http://ant.apache.org/manual/Tasks/sshexec.html

```
<target name="sshexec">
	 <sshexec host="192.168.0.175"
		username="uu"
		password="123"
		command="touch somefile;ls;df -h;" trust="true"/>
</target>
```

 

若个命令可以用;号隔开。

 

关于拷贝远程到本地，拷贝本地到远程，选取特定文件等等，都是变通可行的，本文就不再演示了。