简体   繁体   中英

Read a file from Linux Server through java program

I have my Java Program which is running on the windows machine. From this Window machine i need to read a file from the Linux server. I have write this code to authenticate with the Linux Server, and its working fine

session = jsch.getSession("root", "ServerIP", 22);
            session.setConfig("StrictHostKeyChecking", "no");
            session.setPassword("Passwrod");
            session.connect();
            System.out.println("Server is connect");

I can see "Server is connect" is printing on my machine that's mean authentication is done with the server. And now there is need to read the file from this server and i have write this code

try
            {
            File file = new File("/var/log//callrec/core1.log");
            LineNumberReader sc = new LineNumberReader(new FileReader(file));
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }

But its throwing file not found exception. Can any body guide me how can i solve this.

According to http://www.jcraft.com/jsch/examples/ScpFrom.java.html , you need to execute a command on the remote side through your session object, then get the input and output streams to communicate with the remote command, and read the file meta data and contents through these channels:

...
String command = "scp -f /var/log/callrec/core1.log";
Channel channel = session.openChannel("exec");
((ChannelExec)channel).setCommand(command);

OutputStream out = channel.getOutputStream();
InputStream in = channel.getInputStream();

channel.connect();

// Now use in and out to read the file, 
// see http://www.jcraft.com/jsch/examples/ScpFrom.java.html for a complete example
...

Once you're logged in via SSH, your Java code isn't magically transported in the Linux server context. So when you're using Java tools to read files, it searches the file on your local machine.

You have then at least two possibilities :

1/ Copying the file from the Linux server then work on it. You can better use SFTP rather than SSH if it's the only command you send ( JSCH example here )

2/ Connecting to the Linux server like you do, then streaming the file back to your machine by lauching a cat myFile command and reading the outputStream of the SSH session

My vote would be for the first method, which is cleaner.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM