从远程Python脚本返回值

时间:2014-11-06 10:59:47

标签: java python ssh remote-access jsch

我通过JSch从本地Java代码调用远程Python脚本。 当我执行" ls"从Python上的Java框中,它返回正确的结果(连接工作)。然后我写了一个小程序,返回字符串" hello world"。在Java方面,结果为空白。通常,如果在终端上输出了某些内容,则会返回该内容,但不会返回变量。

Java代码:

import com.jcraft.jsch.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

public class SSHManager
{
private static final Logger LOGGER = Logger.getLogger(SSHManager.class.getName());
private JSch jschSSHChannel;
private String strUserName;
private String strConnectionIP;
private int intConnectionPort;
private String strPassword;
private Session sesConnection;
private int intTimeOut;

private void doCommonConstructorActions(String userName, String password,
        String connectionIP, String knownHostsFileName)
{
    jschSSHChannel = new JSch();

    try
    {
        jschSSHChannel.setKnownHosts(knownHostsFileName);
    }
    catch(JSchException jschX)
    {
        logError(jschX.getMessage());
    }

    strUserName = userName;
    strPassword = password;
    strConnectionIP = connectionIP;
}

public SSHManager(String userName, String password, 
        String connectionIP, String knownHostsFileName)
{
    doCommonConstructorActions(userName, password, 
            connectionIP, knownHostsFileName);
    intConnectionPort = 22;
    intTimeOut = 60000;
}

public SSHManager(String userName, String password, String connectionIP, 
        String knownHostsFileName, int connectionPort)
{
    doCommonConstructorActions(userName, password, connectionIP, 
            knownHostsFileName);
    intConnectionPort = connectionPort;
    intTimeOut = 60000;
}

public SSHManager(String userName, String password, String connectionIP, 
        String knownHostsFileName, int connectionPort, int timeOutMilliseconds)
{
    doCommonConstructorActions(userName, password, connectionIP, 
            knownHostsFileName);
    intConnectionPort = connectionPort;
    intTimeOut = timeOutMilliseconds;
}

public String connect()
{
    String errorMessage = null;

    try
    {
        sesConnection = jschSSHChannel.getSession(strUserName, 
                strConnectionIP, intConnectionPort);
        sesConnection.setPassword(strPassword);
        // UNCOMMENT THIS FOR TESTING PURPOSES, BUT DO NOT USE IN PRODUCTION
        // sesConnection.setConfig("StrictHostKeyChecking", "no");

        java.util.Properties config = new java.util.Properties(); 
        config.put("StrictHostKeyChecking", "no");
        sesConnection.setConfig(config);

        sesConnection.connect(intTimeOut);
    }
    catch(JSchException jschX)
    {
        System.out.println("Connection failed.");
        errorMessage = jschX.getMessage();
    }

    return errorMessage;
}

private String logError(String errorMessage)
{
    if(errorMessage != null)
    {
        LOGGER.log(Level.SEVERE, "{0}:{1} - {2}", 
                new Object[]{strConnectionIP, intConnectionPort, errorMessage});
    }

    return errorMessage;
}

private String logWarning(String warnMessage)
{
    if(warnMessage != null)
    {
        LOGGER.log(Level.WARNING, "{0}:{1} - {2}", 
                new Object[]{strConnectionIP, intConnectionPort, warnMessage});
    }

    return warnMessage;
}

public String sendCommand(String command)
{
    StringBuilder outputBuffer = new StringBuilder();

    try
    {
        Channel channel = sesConnection.openChannel("exec");
        ((ChannelExec)channel).setCommand(command);
        channel.connect();
        InputStream commandOutput = channel.getInputStream();
        int readByte = commandOutput.read();

        while(readByte != 0xffffffff)
        {
            outputBuffer.append((char)readByte);
            readByte = commandOutput.read();
        }

        channel.disconnect();
    }
    catch(IOException ioX)
    {
        logWarning(ioX.getMessage());
        return null;
    }
    catch(JSchException jschX)
    {
        logWarning(jschX.getMessage());
        return null;
    }

    return outputBuffer.toString();
}

public void close()
{
    sesConnection.disconnect();
}
}

测试代码:

import static org.junit.Assert.*;
import org.junit.Test;

public class SSHManagerTest {
/**
 * Test of sendCommand method, of class SSHManager.
 */
@Test
public void testSendCommand()
{
    System.out.println("sendCommand");

    String command = "python /home/abc/helloworld.py";
    String userName = "abc";
    String password = "pqr";
    String connectionIP = "10.112.1.2";
    SSHManager instance = new SSHManager(userName, password, connectionIP, "");
    String errorMessage = instance.connect();

    if(errorMessage != null)
    {
        System.out.println(errorMessage);
        fail();
    }

    //String expResult = "thisOne\n";
    // call sendCommand for each command and the output 
    //(without prompts) is returned
    String result = instance.sendCommand(command);
    System.out.println(result + " (expected hello world)");
    // close only after all commands are sent
    instance.close();
    assertEquals(expResult, result);
}
}

Python代码:

#!/usr/bin/python
def main():
    return "Hello world"

1 个答案:

答案 0 :(得分:0)

脚本

#!/usr/bin/python
def main():
    return "Hello world"

不会向stdout生成任何输出,即return只返回一个值,它不会在stdout上打印它。你可以试试这个:

#!/usr/bin/env python
def main():
    print("Hello world")

请注意,我还将“shebang”更改为使用env。这通常是一种更可靠的方式来调用python,因为它避免了路径问题。