ant使用ssh和linux交互 如:上傳文件

轉載自:http://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->preferences->ant->runtime->classpath中加入jsch-0.1.43.jar

 

例子,可以採用http://ant.apache.org/manual/Tasks/scp.html裏面的examples,還挺全的,拷貝單個文件,拷貝文件夾,設置密碼,設置私鑰等

scp

下面親自測試幾個:

Xml代碼  收藏代碼
  1. <target name="scp-file">  
  2.     <scp file="jar/fetch.jar" todir="uu:[email protected]:/home/uu/fetch" />  
  3. </target>  
  4.   
  5. <target name="scp-folder">  
  6.         <scp todir="uu:[email protected]:/home/uu/fetch" >  
  7.              <fileset dir="jar"/>  
  8.         </scp>  
  9. </target>  

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

 

會有以上的異常,奇怪的官方文檔不說。要求你所連接的host必須存在於你的knownhosts文件中,並且 這個文件也必須是存在的,否則會出現上面的異常。

 

解決方法:

 

Xml代碼  收藏代碼
  1.     <target name="scp-file">  
  2.         <scp file="jar/fetch.jar" todir="uu:[email protected]:/home/uu/fetch" <span style="color: #ff0000;">trust="true"</span>  
  3. />  
  4.     </target>  
  5.      
  6.     <target name="scp-folder">  
  7.             <scp todir="uu:[email protected]:/home/uu/fetch" <span style="color: #ff0000;">trust="true"</span>  
  8. >  
  9.                  <fileset dir="jar"/>  
  10.             </scp>  
  11.     </target>  

 

sshexec

再測試一下誘惑人的可執行shell功能,文檔地址;http://ant.apache.org/manual/Tasks/sshexec.html

Xml代碼  收藏代碼
  1. <target name="sshexec">  
  2.      <sshexec host="192.168.0.175"  
  3.         username="uu"  
  4.         password="123"  
  5.         command="touch somefile;ls;df -h;" trust="true"/>  
  6. </target>  
 

若個命令可以用;號隔開。

 

關於拷貝遠程到本地,拷貝本地到遠程,選取特定文件等等,都是變通可行的,本文就不再演示了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章