1 Eylül 2014 Pazartesi

Java ile Uzak Masaüstü Komut Satırında İşlemler

Bazı durumlarda bir batch program ile server'a bağlanıp belli komutlar çalıştırmamız gerekebilir. Kopyalama, backup alma vb işlemleri otomatize etmenizde faydalı olacaktır.

Aşağıdaki ekran çıktısında linux server'a bağlanıp örnek olarak 'ls' komutunu çalıştırdım. Uygulamayı jar olarakta projenize dahil edebilirsiniz. İşletim sistemi bağımsız olarak kullanabilirsiniz. 


Exec.java
RemoteExecuteCommand\src\main\java\com\blogtest\ex\RemoteExecEx\Exec.java
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.blogtest.ex.RemoteExecEx;

/**
 *
 * @author BeytullahC
 */
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;
import java.io.IOException;
import java.io.InputStream;

public class Exec {

    /**
     *
     * @param hostName for Example : localhost
     * @param username for Example : root
     * @param password for Example : password
     * @param channelType for Example : exec
     * @param command for Example : ls
     */
    public static void exec(String hostName,
            String username,
            String password,
            String channelType,
            String command) {
        try {
            JSch jsch = new JSch();

            String host = null;

            host = username + "@" + hostName; // enter username and ipaddress for machine you need to connect

            String user = host.substring(0, host.indexOf('@'));
            host = host.substring(host.indexOf('@') + 1);

            Session session = jsch.getSession(user, host, 22);

            // username and password will be given via UserInfo interface.
            UserInfo ui = new MyUserInfo(password);
            session.setUserInfo(ui);
            session.connect();

            Channel channel = session.openChannel(channelType);
            ((ChannelExec) channel).setCommand(command);

            channel.setInputStream(null);

            ((ChannelExec) channel).setErrStream(System.err);

            InputStream in = channel.getInputStream();

            channel.connect();

            byte[] tmp = new byte[1024];
            while (true) {
                while (in.available() > 0) {
                    int i = in.read(tmp, 0, 1024);
                    if (i < 0) {
                        break;
                    }
                    System.out.print(new String(tmp, 0, i));
                }
                if (channel.isClosed()) {
                    System.out.println("exit-status: " + channel.getExitStatus());
                    break;
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ee) {
                    ee.printStackTrace(System.err);
                }
            }
            channel.disconnect();
            session.disconnect();
        } catch (JSchException | IOException e) {
            System.out.println(e);
        }
    }

    public static class MyUserInfo implements UserInfo {

        public MyUserInfo(String passwd) {
            this.passwd = passwd;
        }

        @Override
        public String getPassword() {
            return passwd;
        }

        @Override
        public boolean promptYesNo(String str) {
            str = "Yes";
            return true;
        }

        protected String passwd;

        @Override
        public String getPassphrase() {
            return null;
        }

        @Override
        public boolean promptPassphrase(String message) {
            return true;
        }

        @Override
        public boolean promptPassword(String message) {
//            passwd = message;// enter the password for the machine you want to connect.
            return true;
        }

        @Override
        public void showMessage(String message) {
            System.out.println("SHOW MESSAGE " + message);
        }

    }
}

RemoteExecuteCommand\src\main\java\com\blogtest\ex\RemoteExecEx\ExecTest.java
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.blogtest.ex.RemoteExecEx;

/**
 *
 * @author BeytullahC
 */
public class ExecTest {
    public static void main(String[] args) {
        //Exec.exec("hostName-or-ip", "username", "password", "exec", "ls");
    }
}

RemoteExecuteCommand\pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.blogtest.ex</groupId>
    <artifactId>RemoteExecuteCommand</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <dependencies>
        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.50</version>
            <type>jar</type>
        </dependency>
    </dependencies>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>
</project>

Kaynak Kod : https://drive.google.com/file/d/0BxhjtDmkuDJtendPVFYtVVAzUWc/edit?usp=sharing

Hiç yorum yok:

Yorum Gönder