轉自:http://www.blogjava.net/unmi/archive/2006/01/03/124033.html
現在我們安裝linux的時候通常考慮到安全因素(預設情況下)是不打開telnet服務的,而ssh服務是有的,ant很早就支援telnet,但要求我們在linux下要安裝telnet-server,并要啟用該服務。
還好自ant1.60開始支援了ssh 及scp 操作了,早在ant之前若要支援ssh、scp、sftp等任務就必須下載下傳j2ssh的j2ssh-ant.jar和j2ssh-core.jar(在http://www.sourceforge.net的j2ssh下有下載下傳)。現在可以使用ant提供的sshexec和scp任務,由$ant_home/lib/ant-jsch.jar提供支援,但是同樣你也要在http://www.jcraft.com/jsch/index.html下載下傳一個依靠包jsch-0.1.24.jar(檔案名因版本而不同),jsch同樣也是http://www.sourceforge.net下的一個項目。
你需要把下載下傳的jsch-0.1.24拷貝到$ant_home/lib下,假如是eclipse下的ant環境必須在window->preferences->ant->runtime->classpath中加入jsch-0.1.24。
jsch是一個ssh2的純java實作
jsch答應你連接配接到sshd server并采用端口映射, x11 映射; scp檔案傳輸等,你可以把內建jsch提供的功能到你自己的java項目中,jsch 的授權方式為 bsd形式。
下面是用jsch完成sshexec和scp兩個任務的最簡單例子,假如需要更具體的内容,請參考ant使用者手冊
[sshexec任務]
<br><target name="sshexec">
<sshexec host="192.168.122.180" username="root" password="123456"
trust="true" command="cd /;ls"/>
</target>
注 意上面的trust屬性一般設定為true, 假如為預設值false時,那麼就要求你所連接配接的host必須存在于你的knownhosts檔案中,并且 這個檔案也必須是存在的,否則會出現 com.jcraft.jsch.jschexception: reject hostkey: 192.168.122.180異常。執行linux下的指令時可以用分号";"把多個指令隔開,它們将會依次執行,而不需要寫多個sshexec進行多 次連接配接,每次連接配接隻執行一個指令。
該任務的執行後輸出結果如下:
sshexec:
[sshexec] connecting to 192.168.122.180:22
[sshexec] backup
[sshexec] bin
[sshexec] boot
[sshexec] dev
[sshexec] etc
...................
[scp任務]
1.拷貝單個檔案到遠端伺服器
<scp file="c:/cmd.txt" todir="root:[email protected]:/tmp" trust="true"/>
或
<scp file="c:/cmd.txt" todir="[email protected]:/tmp" password="123456" trust="true"/>
2.拷貝遠端檔案本地
<scp file="root:[email protected]:/tmp/cmd.txt" todir="d:/my-app" trust="true"/>
3.拷貝遠端目錄到本地,将以遞歸形式操作
<scp file="root:[email protected]:/tmp*.java" />
</fileset>
</scp>
或
<scp todir="root:[email protected]:/tmp" trust="true">
<fileset dir="d:/my-app" excludes="**/*.java"/>
</scp>
最後一個任務的執行輸出結果如下(其他略):
scp:
[scp]connecting to 192.168.122.180:22
[scp] sending: cmd.txt : 0
[scp] file transfer time: 0.0 average rate: ? b/s
[scp] sending: pom.xml : 852
[scp] file transfer time: 0.0 average rate: ∞ b/s
[scp] sending: application.properties : 142
[scp] file transfer time: 0.0 average rate: ∞ b/s
[scp] sending: application.properties : 45
[scp] file transfer time: 0.0 average rate: ∞ b/s
[scp] sending: test.properties : 0
[scp] file transfer time: 0.02 average rate: 0.0 b/s
[scp] sending: application.properties : 153
[scp] file transfer time: 0.0 average rate: ∞ b/s
[scp] sending: application.properties : 45
[scp] file transfer time: 0.0 average rate: ∞ b/s
[scp] done.
[unmi 後注]前面的内容很多都是直接在這裡可視化編輯的,如改變字型顔色,大小什麼的,這樣做發現生成的html垃圾代碼實在是太多,以後對于内容稍稍豐富的文 章還是在外部編輯器如dreamweaver編輯好了再貼到這裡好一點,并且更能作本地備份,以免意外,當然簡單内容這裡直接寫也無妨。