C # access an SFTP server based on public key authentication

Source: Internet
Author: User
Tags file transfer protocol ftp protocol

What is SFTP, Public Key Authentication,

SFTP is not an extension of the FTP protocol. It is a File Transfer Protocol Based on SSH. When the SFTP server has a public key for logging on to the client, the client can use its own private key to shake hands with the server. This method is called public key authentication.

1. Create an SFTP Server

First of all, you must first create a local SFTP server. I use silvershield. If it is not commercially available, it is free of charge. Of course, you can only download and install three connections at the same time.

 

2. Configure the server

Open "silvershield Management Console" and connect

 

Set Log Path, switch to user, and append

Username and so on.

The key is in manage user's public keys. Open, add

The formal process should be that the customer uses winscp and other tools to generate their own key-pair, and then the public can be pasted to the actual public key, which can be used for testing by the users themselves, so generate directly,

Then you will be prompted to save the private key, which must be selectedOpenSSH Private Key Files. The generated file is the Private Key used for client authentication.

Click "Confirm" in sequence to complete the configuration.

 

3. Download the SFTP Library

I am using SSH. Net Library.

 

4. Access Code

A. Another customer may use ftp to create a common interface first:

Public interface iftpclient {// <summary> // connect to the server // </Summary> /// <returns> true: success; false: failed </returns> bool connect (); // <summary> // disconnect /// </Summary> void disconnect (); /// <summary> /// obtain the file list /// </Summary> /// <Param name = "path"> path </param> /// <returns> </returns> List <string> listfiles (string path ); /// <summary> /// download the file /// </Summary> /// <Param name = "remotefilename"> contains the full-path server-side file name </param> /// <Param name = "localfilename"> local file name </param> /// <returns> </returns> bool download (string remotefilename, string localfilename ); /// <summary> /// upload a file /// </Summary> /// <Param name = "localfilename"> file to be uploaded </param> /// <Param name = "remotefilename"> Server File name </param> // <returns> </returns> bool upload (string localfilename, string remotefilename ); /// <summary> // rename the file /// </Summary> /// <Param name = "localfilename"> name of the source file containing the full path </param>/ // <Param name = "remotefilename"> New file name containing the full path </param> /// <returns> </returns> bool Rename (string orgfilename, string newfilename ); /// <summary> /// delete a file /// </Summary> /// <Param name = "orgfilename"> </param> /// <Param name = "newfilename"> </param> // <returns> </returns> bool Delete (string filename );}

 

B definition implementation:

Public class SFtpClient: IFtpClient {SftpClient sftp = null; /// <summary> /// constructor /// </summary> /// <param name = "host"> sftp server name or IP address </param> // /<param name = "port"> port, 22 by default </param> /// <param name = "user"> </param> /// <param name = "privateKey"> </param> /// <param name = "passPhrase"> </param> public SFtpClient (string host, int? Port, string user, string privateKey, string passPhrase) {PrivateKeyFile keyFile = null; if (string. isNullOrEmpty (passPhrase) {keyFile = new PrivateKeyFile (privateKey);} else {keyFile = new PrivateKeyFile (privateKey, passPhrase);} if (port. hasValue) {sftp = new SftpClient (host, port. value, user, keyFile);} else {sftp = new SftpClient (host, user, keyFile);} if (sftp! = Null) {sftp. connectionInfo. retryAttempts = 5; sftp. connectionInfo. timeout = new TimeSpan (0, 3, 0) ;}} public bool Connect () {if (sftp = null) {return false;} if (sftp. isConnected) {return true;} try {sftp. connect (); return true;} catch (Exception ex) {string server = string. format ("{0 }:{ 1}", sftp. connectionInfo. username, sftp. connectionInfo. host); // I use nLog to record error logs. // Logger. Error ("[{0}] SFTP connection Error. ", Server, ex); return false ;}} public void DisConnect () {if (sftp = null) {return ;} if (! Sftp. isConnected) {return;} try {sftp. disconnect (); sftp. dispose (); sftp = null;} catch (Exception ex) {// logger. error ("SFTP disconnection Error. ", Ex );}} /// <summary> /// obtain the file list /// </summary> /// <param name = "path"> path </param> /// <returns> </returns> public List <string> ListFiles (string path) {if (! Connect () {return null;} List <string> files = new List <string> (); try {sftp. changeDirectory ("/"); sftp. listDirectory (path ). toList (). forEach (f => {files. add (f. fullName) ;}); return files;} catch (Exception ex) {// logger. error ("[{0}] An Error occurred while obtaining the file list. ", Path, ex); return null ;}} /// <summary> /// download the file /// </summary> /// <param name = "remoteFileName"> contains the full-path server-side file name </param> /// <param name = "localFileName"> local file name </param> /// <returns> </returns> public bool Download (string remoteFileName, string localFileName) {if (! Connect () {return false;} try {sftp. changeDirectory ("/"); FileStream fs = File. openWrite (localFileName); sftp. downloadFile (remoteFileName, fs); fs. close (); return true;} catch (Exception ex) {// logger. error ("[{0}] File Download Error. ", RemoteFileName, ex); return false ;}} /// <summary> /// upload a file /// </summary> /// <param name = "localFileName"> file to be uploaded </param> /// <param name = "remoteFileName"> Server File name </param> // <returns> </returns> public bool Upload (string localFileName, string remoteFileName) {if (! Connect () {return false;} try {sftp. changeDirectory ("/"); FileStream fs = File. openRead (localFileName); sftp. uploadFile (fs, remoteFileName, true); fs. close (); Thread. sleep (1000); return true;} catch (Exception ex) {// logger. error ("[{0}] File Upload Error. ", LocalFileName, ex); return false ;}} /// <summary> // rename the file /// </summary> /// <param name = "localFileName"> name of the source file containing the full path </param>/ // <param name = "remoteFileName"> New file name containing the full path </param> /// <returns> </returns> public bool Rename (string orgFileName, string newFileName) {if (! Connect () {return false;} try {sftp. changeDirectory ("/"); sftp. renameFile (orgFileName, newFileName); return true;} catch (Exception ex) {// logger. error ("[{0}] file renaming Error. ", LocalFileName, ex); return false ;}} /// <summary> /// delete a file /// </summary> /// <param name = "orgFileName"> </param> /// <param name = "newFileName"> </param> // <returns> </returns> public bool Delete (string fileName) {if (! Connect () {return false;} try {sftp. changeDirectory ("/"); sftp. deleteFile (fileName); return true;} catch (Exception ex) {// logger. error ("[{0}] File Deletion Error. ", LocalFileName, ex); return false ;}}}

Download example

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.