Modifying a remote file while connected to a server through SSH using .NET
In general, to modify remote files, use SFTP. In SSH.NET that's what SftpClient
is for.
Though as you seem to need to use elevated privileges (su
) – an important factor that your question title fails to mention – it's way more difficult. The right solution is to avoid the need for su
. See somewhat related:
Allowing automatic command execution as root on Linux using SSH.
Another option would be to try to execute the SFTP server under su
. Though that would require modification of SSH.NET code. See related Java question:
Using JSch to SFTP when one must also switch user
If you want to keep your current shell approach with su
, you are stuck with simulating shell commands. Note that connecting to SSH server won't make other .NET classes (like the File
) magically be able to work with remote files (even if SFTP was possible, let only when it is not, due to the su
requirement).
The easiest way to read remote file using shell is using the cat
command:
cat /home/user/test.properties
How to write a string to a file located in remote server (linux)
ChannelSftp has versions of the put method which accept a filename on the remote system and which return an OutputStream. Anything written to the OutputStream is written to the file on the remote system. You can write binary data to an OutputStream, or convert it to a Writer if you want to write text to it:
try (OutputStream out = channelSftp.put("/some/remote/file")) {
OutputStreamWriter writer = new OutputStreamWriter(out);
writer.write("some text");
} catch (IOException e) {
....
}
Paramiko's SSHClient with SFTP
paramiko.SFTPClient
Sample Usage:
import paramiko
paramiko.util.log_to_file("paramiko.log")
# Open a transport
host,port = "example.com",22
transport = paramiko.Transport((host,port))
# Auth
username,password = "bar","foo"
transport.connect(None,username,password)
# Go!
sftp = paramiko.SFTPClient.from_transport(transport)
# Download
filepath = "/etc/passwd"
localpath = "/home/remotepasswd"
sftp.get(filepath,localpath)
# Upload
filepath = "/home/foo.jpg"
localpath = "/home/pony.jpg"
sftp.put(localpath,filepath)
# Close
if sftp: sftp.close()
if transport: transport.close()
How to retrieve a file from a server via SFTP?
Another option is to consider looking at the JSch library. JSch seems to be the preferred library for a few large open source projects, including Eclipse, Ant and Apache Commons HttpClient, amongst others.
It supports both user/pass and certificate-based logins nicely, as well as all a whole host of other yummy SSH2 features.
Here's a simple remote file retrieve over SFTP. Error handling is left as an exercise for the reader :-)
JSch jsch = new JSch();
String knownHostsFilename = "/home/username/.ssh/known_hosts";
jsch.setKnownHosts( knownHostsFilename );
Session session = jsch.getSession( "remote-username", "remote-host" );
{
// "interactive" version
// can selectively update specified known_hosts file
// need to implement UserInfo interface
// MyUserInfo is a swing implementation provided in
// examples/Sftp.java in the JSch dist
UserInfo ui = new MyUserInfo();
session.setUserInfo(ui);
// OR non-interactive version. Relies in host key being in known-hosts file
session.setPassword( "remote-password" );
}
session.connect();
Channel channel = session.openChannel( "sftp" );
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
sftpChannel.get("remote-file", "local-file" );
// OR
InputStream in = sftpChannel.get( "remote-file" );
// process inputstream as needed
sftpChannel.exit();
session.disconnect();
How to transfer a file to ssh server in an ssh-connection made by paramiko?
Try this:
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
s.connect("xxx.xxx.xxx.xxx",22,username=xxx,password='',timeout=4)
sftp = s.open_sftp()
sftp.put('/home/me/file.ext', '/remote/home/file.ext')
Related Topics
Mq Explorer - Could Not Load Swt Library
Implementation of Function Execve (Unistd.H)
Linux Kill Process Using Timeout in Milliseconds
Sublime Text 2 Build (Ctrl +B) Intel Fortran Compiler
Reading Microphone Data by Polling Using Alsa [Or V4L2]
Find All Instances of Word Occurring in a File
Linux Allocates Memory at Specific Physical Address
Sonarqube Does Not Come Back Up After I Enable Postgres and Set Sonar.Properties
Reducing Privileges of a Process on Unix or Gnu/Linux
Sending Data on Af_Packet Socket
Watchman Makes Fsnotify Spuriously Detect File Changes
Why Does Printf Still Work with Rax Lower Than The Number of Fp Args in Xmm Registers
Linux Clipboard Read/Write in C
Floating Point Exception (Core Dumped) While Doing Division in Assembly