【Eclipse】Eclipse/Antで、SSHを使ってファイル転送/実行を行う

使用するAntタスク

scpタスク

 * scpコマンド(※)を利用して、ファイル転送する

 ※ sshを利用してリモートマシン間でファイルコピーするコマンド
構文
<scp todir="【ユーザ】:【パスワード】@【ホスト/IP】:【パス】" port="【実行するポート】"
  trust="true" file="【ファイル転送するファイルパス】" />

sshexecタスク

 * ssh経由でコマンド実行する
構文
<sshexec username="【ユーザ】" password="【パスワード】" host="【ホスト/IP】" port="【実行するポート】"
 trust="yes" command="【実行コマンド1】; 【実行コマンド2】;・・・ 【実行コマンドX】;" />

設定手順

 * Eclipseでの設定を行う

前提条件

 * Eclipse をインストールしてある

手順

[1] 以下のサイトから 最新の jsch をダウンロードする(今回は「jsch-0.1.54.jar」)
http://mvnrepository.com/artifact/com.jcraft/jsch
[2] Eclipseを起動し、[Window]-[Preferences]-[Ant]-[Runtime]-[Classpath]-[Ant Home Entities(Default)]
    -[Add External JARS]を選択し、[1]でダウンロードしたJARファイルを指定する

サンプル

設定環境

 * OS : Windows10
 * Java : Java1.8
 * Eclipse : Eclipse Nano1
 * jsch : jsch-0.1.54.jar
 * デプロイ先のOS : CentOS7

build.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project basedir="." default="helloworld" name="Demo">
  <!-- HOST -->
  <property name="connect.host" value="XXX.XXX.XXX.XXX" />
  <!-- User -->
  <property name="connect.user" value="root" />
  <!-- Password -->
  <property name="connect.pwd" value="password" />
  <!-- SSH Port -->
  <property name="connect.port" value="22" />
  <property name="shell.path" location="${basedir}/etc/helloworld.sh" />

  <!--  -->
  <target name="helloworld">
    <!-- SCP送信 -->
    <echo message="path = ${shell.path}" />
    <scp todir="${connect.user}:${connect.pwd}@${connect.host}:/root/" port="${connect.port}"
      trust="true" file="${shell.path}" />

    <!-- SSH実行 -->
    <sshexec username="${connect.user}" password="${connect.pwd}" host="${connect.host}"
      port="${connect.port}" trust="yes" command="chmod +x ~/helloworld.sh; ~/helloworld.sh" />
  </target>
</project>

helloworld.sh

echo "Hello World!"

出力結果

Antを実行するために、「build.xml」を右クリックし、[Run]で実行する
Buildfile: C:\workspace\Demo\build.xml
helloworld:
     [echo] path = C:\workspace\Demo\etc\helloworld.sh
      [scp] Connecting to XXX.XXX.XXX.XXX:22
      [scp] done.
  [sshexec] Connecting to XXX.XXX.XXX.XXX:22
  [sshexec] cmd : chmod +x ~/helloworld.sh; ~/helloworld.sh
  [sshexec] Hello World!
BUILD SUCCESSFUL
Total time: 6 seconds

トラブルシューティング

Antを実行後に、エラーが表示する

エラー内容
Variable references non-existent resource : ${workspace_loc:/Tomcat/build.xml}.
解決案
 * Eclipseを起動し、[Window]-[Preferences]-[Ant]-[Runtime]-[Classpath]-[Ant Home Entities(Default)]
   で「${workspace_loc:/Tomcat/build.xml」があるので、選択した状態で「Remove」ボタン押下し
  「OK」ボタン押下