public static void CreateTreeFolderFromSFTP(ChannelSftp sftpHandler, string initialFileDestination, string initialDir, string filePath, ref string fileDestination) { string[] folders = filePath.Replace(initialDir, string.Empty) .Replace('\\', '/') .Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); var count = 1; var treeSource = initialFileDestination; foreach (var folder in folders) { if (folders.Length == count) { break; } treeSource = string.Format("{0}{1}/", treeSource, folder); if (!sftpHandler.isRemoteDir(treeSource)) { sftpHandler.mkdir(treeSource); } count++; } fileDestination = string.Format("{0}{1}", initialFileDestination, filePath.Replace(initialDir, string.Empty).Replace('\\', '/')); }
private void ConnectServer() { SshConnectionInfo info = new SshConnectionInfo { User = "******", Pass = null, Host = "up.bakery.moe", IdentityFile = PrivateKeyPath, }; helper = new SFTPHelper(info, OnStart, OnProgress, null); helper.Connect(); ChannelSftp c = helper.Sftp.SftpChannel; c.cd("www/creator/windows"); byte[] b = EncodeInfoFile(); foreach (var file in _list) { helper.Upload(new MemoryStream(file.Value), file.Key); helper.Sftp.Cancel(); } helper.Upload(new MemoryStream(b), INFO_FILE); helper.Close(); helper = null; Invoke(new MethodInvoker(() => { textBox2.Text += "上传完成。" + Environment.NewLine; WriteVersionFile(); Clear(); button1.Enabled = true; })); }
public NtStatus SetEndOfFile( string filename, long length, DokanFileInfo info) { try { string path = GetPath(filename); ChannelSftp channel = GetChannel(); SftpATTRS attr = channel.stat(path); attr.setSIZE(length); channel.setStat(path, attr); return(NtStatus.Success); } catch (SftpException) { return(NtStatus.Error); } catch (Exception e) { connectionError_ = true; Debug(e.ToString()); Reconnect(); return(NtStatus.Error); } }
public int MoveFile( String filename, String newname, bool replace, DokanFileInfo info) { Debug("MoveFile {0}", filename); try { string oldPath = GetPath(filename); string newPath = GetPath(newname); ChannelSftp channel = GetChannel(); channel.rename(oldPath, newPath); return(0); } catch (SftpException) { return(-1); } catch (Exception e) { connectionError_ = true; Debug(e.ToString()); Reconnect(); return(-1); } }
public int SetFileAttributes( String filename, FileAttributes attr, DokanFileInfo info) { Debug("SetFileAttributes {0}", filename); try { string path = GetPath(filename); ChannelSftp channel = GetChannel(); SftpATTRS sattr = channel.stat(path); int permissions = sattr.getPermissions(); Debug(" permissons {0} {1}", permissions, sattr.getPermissionsString()); sattr.setPERMISSIONS(permissions); channel.setStat(path, sattr); return(0); } catch (SftpException) { return(-1); } catch (Exception e) { connectionError_ = true; Debug(e.ToString()); Reconnect(); return(-1); } }
/// <summary> /// 释放SFTP连接 /// </summary> public void Dispose() { this.DisconnectSFTP(); this._channel = null; this._session = null; this._channelSftp = null; }
public int CreateDirectory( String filename, DokanFileInfo info) { Debug("CreateDirectory {0}", filename); try { string path = GetPath(filename); ChannelSftp channel = GetChannel(); channel.mkdir(path); return(0); } catch (SftpException e) { Debug(e.ToString()); return(-1); } catch (Exception e) { connectionError_ = true; Debug(e.ToString()); Reconnect(); return(-1); // TODO: more appropriate error code } }
static void Main(string[] args) { Sftp sftp = new Sftp(SFTPConnectSample.Properties.Settings.Default.HostName, SFTPConnectSample.Properties.Settings.Default.UserName, SFTPConnectSample.Properties.Settings.Default.Password); sftp.Connect(); #region Require if you want to delete Files JSch objjsh = new JSch(); Session session = objjsh.getSession(SFTPConnectSample.Properties.Settings.Default.UserName, SFTPConnectSample.Properties.Settings.Default.HostName); // Get a UserInfo object UserInfo ui = new UInfo(SFTPConnectSample.Properties.Settings.Default.Password);; // Pass user info to session session.setUserInfo(ui); // Open the session session.connect(); Channel channel = session.openChannel("sftp"); ChannelSftp cSftp = (ChannelSftp)channel; cSftp.connect(); #endregion ArrayList res = sftp.GetFileList(SFTPConnectSample.Properties.Settings.Default.FromPath + "*.xml"); foreach (var item in res) { if (item.ToString() != "." && item.ToString() != "..") { //File Copy from Remote sftp.Get(SFTPConnectSample.Properties.Settings.Default.FromPath + item, Path.Combine(Application.StartupPath, SFTPConnectSample.Properties.Settings.Default.DirectoryPath + "/" + item)); //File Delete from Remote cSftp.rm(SFTPConnectSample.Properties.Settings.Default.FromPath + item); //Upload File sftp.Put(Path.Combine(Path.Combine(Application.StartupPath, "XMLFiles"), item.ToString()), SFTPConnectSample.Properties.Settings.Default.ToPath + item); } } channel.disconnect(); cSftp.exit(); sftp.Close(); }
public string CheckConnectyAndGetFileList() { try { //首先连接 if (!Connected) { m_session.connect(); m_channel = m_session.openChannel("sftp"); m_channel.connect(); m_sftp = (ChannelSftp)m_channel; } //其次获取根目录 Tamir.SharpSsh.java.util.Vector vvv = m_sftp.ls("/"); ArrayList objList = new ArrayList(); foreach (Tamir.SharpSsh.jsch.ChannelSftp.LsEntry qqq in vvv) { objList.Add(qqq.getFilename()); } this.Disconnect(); return("Succeed"); } catch (Exception ex) { return(ex.Message); } }
public SftpObjectDatabase(string path, TransportSftp instance) { this._instance = instance; if (path.StartsWith("/~")) { path = path.Substring(1); } if (path.StartsWith("~/")) { path = path.Substring(2); } try { _ftp = instance.NewSftp(); _ftp.cd(path); _ftp.cd("objects"); _objectsPath = _ftp.pwd(); } catch (TransportException) { close(); throw; } catch (SftpException je) { throw new TransportException("Can't enter " + path + "/objects: " + je.message, je); } }
public int SetAllocationSize(string filename, long length, DokanFileInfo info) { try { string path = GetPath(filename); ChannelSftp channel = GetChannel(); SftpATTRS attr = channel.stat(path); if (attr.getSize() < length) { attr.setSIZE(length); } channel.setStat(path, attr); } catch (SftpException) { return(-1); } catch (Exception e) { connectionError_ = true; Debug(e.ToString()); Reconnect(); return(-1); } return(0); }
/// <exception cref="NGit.Errors.TransportException"></exception> internal SftpObjectDB(TransportSftp _enclosing, string path) { this._enclosing = _enclosing; if (path.StartsWith("/~")) { path = Sharpen.Runtime.Substring(path, 1); } if (path.StartsWith("~/")) { path = Sharpen.Runtime.Substring(path, 2); } try { this.ftp = this._enclosing.NewSftp(); this.ftp.Cd(path); this.ftp.Cd("objects"); this.objectsPath = this.ftp.Pwd(); } catch (TransportException err) { this.Close(); throw; } catch (SftpException je) { throw new TransportException("Can't enter " + path + "/objects" + ": " + je.Message , je); } }
/* the only function in the class that delete file on the sftp server */ public static void Delete(string host, string username, string password, string fileName) { JSch js = new JSch(); // declare sftp connection Sftp sftp = new Sftp(host, username, password); sftp.Connect(); // Create a session with SFTP credentials Session session = js.getSession(sftp.Username, sftp.Host); // Get a UserInfo object UserInfo ui = new UInfo(sftp.Password); // Pass user info to session session.setUserInfo(ui); // Open the session session.connect(); // Tell it is an SFTP Channel channel = session.openChannel("sftp"); ChannelSftp cSftp = (ChannelSftp)channel; cSftp.connect(); // Delete the file cSftp.rm(fileName); // disconnection channel.disconnect(); cSftp.exit(); sftp.Close(); }
//测试连接状态 public bool CheckFtpConnectionStatus(out string errmsg) { errmsg = ""; try { if (!Connected) { try { m_session.connect(); m_channel = m_session.openChannel("sftp"); m_channel.connect(); m_sftp = (ChannelSftp)m_channel; return(true); } catch (Exception exConn) { errmsg = "Connect error:" + exConn.Message; return(false); } } else { return(true); } } catch (Exception ex) { errmsg = "Connect error:" + ex.Message.ToString(); return(false); } }
/// <summary> /// Initializes connection to a remote Server with given credentials /// </summary> private void _Init() { if (_jsch != null) { try { Console.WriteLine("Attempting to disconnect"); _sftpSession.disconnect(); _sftpSession = null; _jsch = null; } catch (Exception e) { _sftpSession = null; _jsch = null; Console.WriteLine("There was a failure while restarting connection " + e.Message); } //wait half a second before reconnecting so we dont flood FTP server with continued failed attempts Thread.Sleep(500); } try { _jsch = new JSch(); _sftpSession = _jsch.getSession(_user, _host, _port); _ui = new SftpUserInfo(); // this is needed for the passkey _sftpSession.setUserInfo(_ui); _sftpSession.setPassword(_pass); _sftpSession.connect(); _channel = _sftpSession.openChannel("sftp"); _channel.connect(); _sftpChannel = (ChannelSftp)_channel; //_ins = Console.OpenStandardInput(); //_outs = Console.Out; this.changeRemoteWorkingDirectory(_rootDir); } catch (Exception e) { if (!_reportOnce && _failCount >= 500) { string failMsg = string.Format("SFTP Connection is failing ({2}@{0}:{1}) \n\t{3}", _host, _port, _user, e.Message); GatLogger.Instance.AddMessage(failMsg, LogMode.LogAndScreen); GatLogger.Instance.AddMessage(string.Format("Inner Exception: {0}", e.InnerException)); GatLogger.Instance.AddMessage(string.Format("Exception Stack: {0}", e.StackTrace)); _reportOnce = true; } else { _failCount++; } } }
public int ReadFile( String filename, Byte[] buffer, ref uint readBytes, long offset, DokanFileInfo info) { string path = GetPath(filename); if (path.Contains(":SSHFSProperty.Permission")) { if (offset == 0) { string[] tmp = path.Split(new char[] { ':' }); path = tmp[0]; string str = ReadPermission(path); byte[] bytes = System.Text.Encoding.ASCII.GetBytes(str); uint min = (uint)(buffer.Length < bytes.Length ? buffer.Length : bytes.Length); Array.Copy(bytes, buffer, min); readBytes = min; return(0); } else { readBytes = 0; return(0); } } if (info.IsDirectory) { return(-1); } Debug("ReadFile {0} bufferLen {1} Offset {2}", filename, buffer.Length, offset); try { ChannelSftp channel = GetChannel(); GetMonitor monitor = new GetMonitor(offset + buffer.Length); GetStream stream = new GetStream(buffer); channel.get(path, stream, monitor, ChannelSftp.RESUME, offset); readBytes = (uint)stream.RecievedBytes; Debug(" ReadFile readBytes: {0}", readBytes); return(0); } catch (SftpException) { return(-1); } catch (Exception e) { connectionError_ = true; Debug(e.ToString()); Reconnect(); return(-1); } }
public virtual void FtpPickUp(string destinationFilePath, Dictionary <string, string> config, string fileName) { ChannelSftp channelSftp = null; Channel channel; var printxml = config["printxml"] == "true"; var url = config["sftpUrl"]; var username = config["sftpUsername"]; var password = config["sftpPassword"]; var knownHostsFile = config["knownHostsFile"]; var jsch = new JSch(); jsch.setKnownHosts(knownHostsFile); var session = jsch.getSession(username, url); session.setPassword(password); try { session.connect(); channel = session.openChannel("sftp"); channel.connect(); channelSftp = (ChannelSftp)channel; } catch (SftpException e) { throw new LitleOnlineException("Error occured while attempting to establish an SFTP connection", e); } try { if (printxml) { Console.WriteLine("Picking up remote file outbound/" + fileName + ".asc"); Console.WriteLine("Putting it at " + destinationFilePath); } channelSftp.get("outbound/" + fileName + ".asc", destinationFilePath); if (printxml) { Console.WriteLine("Removing remote file output/" + fileName + ".asc"); } channelSftp.rm("outbound/" + fileName + ".asc"); } catch (SftpException e) { throw new LitleOnlineException( "Error occured while attempting to retrieve and save the file from SFTP", e); } channelSftp.quit(); session.disconnect(); }
/// <summary> /// Attempts to re-establish a connection with a remote server /// </summary> /// <returns>true if re-connection succeded or false if re-connection did not succed</returns> private bool _Reconnect() { try { if (!_sftpSession.isConnected()) { //Attempt to reconnect to server if (_sftpChannel != null) { _sftpChannel.disconnect(); } if (_channel != null) { _channel.disconnect(); } _sftpChannel = null; _channel = null; _sftpSession = null; _jsch = null; _jsch = new JSch(); _sftpSession = _jsch.getSession(_user, _host, 22); _sftpSession.setUserInfo(_ui); _sftpSession.setPassword(_pass); _sftpSession.connect(); _channel = _sftpSession.openChannel("sftp"); _channel.connect(); _sftpChannel = (ChannelSftp)_channel; this.changeRemoteWorkingDirectory(_rootDir); return(true); } } catch (SftpException sftp) { //Sftp Connection return(false); } catch (Exception ex) { if (ex.Message.Contains("actively refused")) { Console.WriteLine("**** FTP error Check machine " + _host + " it may be inactive ******"); } else { Console.WriteLine("An exception occurred while attempting to reconnect on host " + _host + ":" + _user + " :\n" + ex.Message); } return(false); } return(false); }
public bool Connect() { if (!session.isConnected()) { session.connect(); channel = session.openChannel("sftp"); channel.connect(); sftp = (ChannelSftp)channel; } return(true); }
internal OutputStreamPut (ChannelSftp sftp, byte[] handle, long[] _offset, ISftpProgressMonitor monitor) : base() { this.sftp = sftp; this.handle = handle; this._offset = _offset; this.monitor = monitor; }
public int WriteFile( String filename, Byte[] buffer, ref uint writtenBytes, long offset, DokanFileInfo info) { Debug("WriteFile {0} bufferLen {1} Offset {2}", filename, buffer.Length, offset); string path = GetPath(filename); if (path.Contains(":SSHFSProperty.Permission")) { if (offset == 0) { string[] tmp = path.Split(new char[] { ':' }); path = tmp[0]; int permission = 0; permission = Convert.ToInt32(System.Text.Encoding.ASCII.GetString(buffer), 8); WritePermission(path, permission); writtenBytes = (uint)buffer.Length; return(0); } else { writtenBytes = 0; return(0); } } try { ChannelSftp channel = GetChannel(); //GetMonitor monitor = new GetMonitor(buffer.Length); Tamir.SharpSsh.java.io.OutputStream stream = channel.put(path, null, 3 /*HACK: 存在しないモード */, offset); stream.Write(buffer, 0, buffer.Length); stream.Close(); writtenBytes = (uint)buffer.Length; return(0); } catch (IOException) { return(0); } catch (Exception e) { Debug(e.ToString()); return(-1); } }
/// <summary> /// 建立SFTP连接 /// </summary> private void CreateConnectSFTP() { try { _session.connect(); _channel = _session.openChannel("sftp"); _channel.connect(); _channelSftp = (ChannelSftp)_channel; } catch { throw; } }
/// <summary> /// 建立SFTP连接 /// </summary> private void CreateConnectSFTP() { try { _session.connect(); _channel = _session.openChannel("sftp"); _channel.connect(); _channelSftp = (ChannelSftp)_channel; } catch (Exception e) { _log.Error("连接SFTP失败!", e); } }
//连接SFTP public bool Connect() { try { if (!Connected) { m_session.connect(); m_channel = m_session.openChannel("sftp"); m_channel.connect(); m_sftp = (ChannelSftp)m_channel; } return(true); } catch (Exception e) { Debug.Log("connect failed!!" + e); return(false); } }
protected void _Connect() { _jsch = new JSch(); //session.setConfig(); _session = _jsch.getSession(this.Username, this.Host, this.Port); UserInfo ui = new DirectPasswordUserInfo(this.Password); _session.setUserInfo(ui); _session.connect(); _csftp = (ChannelSftp)_session.openChannel("sftp"); _csftp.connect(); //RootPath = csftp.getHome(); RootPath = ""; }
internal SftpLogFileInfoSharpSSH(Uri uri) { this.uri = uri; this.remoteFileName = uri.PathAndQuery; string userName = null; string password = null; if (uri.UserInfo != null && uri.UserInfo.Length > 0) { string[] split = uri.UserInfo.Split(new char[] { ':' }); if (split.Length > 0) { userName = split[0]; } if (split.Length > 1) { password = split[1]; } } if (userName == null || password == null) { IList <string> userNames = new List <string>(); LoginDialog dlg = new LoginDialog(uri.Host, userNames); dlg.UserName = userName; if (DialogResult.OK == dlg.ShowDialog()) { password = dlg.Password; userName = dlg.UserName; } } UserInfo userInfo = new SharpSshUserInfo(userName, password); JSch jsch = new JSch(); int port = uri.Port != -1 ? uri.Port : 22; Session session = jsch.getSession(userName, this.uri.Host, port); session.setUserInfo(userInfo); session.connect(); Channel channel = session.openChannel("sftp"); channel.connect(); this.sftpChannel = (ChannelSftp)channel; SftpATTRS sftpAttrs = this.sftpChannel.lstat(this.remoteFileName); this.originalFileLength = sftpAttrs.getSize(); }
public int SetFileTime( String filename, DateTime ctime, DateTime atime, DateTime mtime, DokanFileInfo info) { Debug("SetFileTime {0}", filename); try { Debug(" filetime {0} {1} {2}", ctime.ToString(), atime.ToString(), mtime.ToString()); string path = GetPath(filename); ChannelSftp channel = GetChannel(); SftpATTRS attr = channel.stat(path); TimeSpan at = (atime - new DateTime(1970, 1, 1, 0, 0, 0)); TimeSpan mt = (mtime - new DateTime(1970, 1, 1, 0, 0, 0)); int uat = (int)at.TotalSeconds; int umt = (int)mt.TotalSeconds; if (mtime == DateTime.MinValue) { umt = attr.getMTime(); } if (atime == DateTime.MinValue) { uat = attr.getATime(); } attr.setACMODTIME(uat, umt); channel.setStat(path, attr); return(0); } catch (SftpException) { return(-1); } catch (Exception e) { connectionError_ = true; Debug(e.ToString()); Reconnect(); return(-1); } }
private bool isExist(string path, DokanFileInfo info) { try { ChannelSftp channel = GetChannel(); SftpATTRS attr = channel.stat(path); if (attr.isDir()) { info.IsDirectory = true; } return(true); } catch (SftpException) { return(false); } }
internal override void Close() { if (this.ftp != null) { try { if (this.ftp.IsConnected()) { this.ftp.Disconnect(); } } finally { this.ftp = null; } } }
/// <summary> /// 连接SFTP /// </summary> public bool Connect() { try { if (!Connected) { m_session.connect(); m_channel = m_session.openChannel("sftp"); m_channel.connect(); m_sftp = (ChannelSftp)m_channel; } return(true); } catch (Exception ex) { throw ex; } }
public runnable2(ChannelSftp channel, PipedOutputStream pos, String _src, SftpProgressMonitor monitor, int mode, Exception[] closed) { this.channel= channel; this.pos=pos; this._src=_src; this.monitor=monitor; this.mode=mode; this.closed=closed; }
public InputStreamGet( ChannelSftp sftp, byte[] handle, long[] _offset, int[] _server_version, SftpProgressMonitor monitor) { this.sftp=sftp; this.handle=handle; this._offset=_offset; this._server_version=_server_version; this.monitor=monitor; }
internal OutputStreamPut(ChannelSftp sftp, byte[] handle, long[] _offset, SftpProgressMonitor monitor) : base() { this.sftp=sftp; this.handle=handle; this._offset=_offset; this.monitor=monitor; }
public InputStreamGet( ChannelSftp sftp, byte[] handle, SftpProgressMonitor monitor) { this.sftp=sftp; this.handle=handle; this.monitor=monitor; }
public runnable1(ChannelSftp channel, PipedInputStream pis, String _dst, SftpProgressMonitor monitor, int mode) { this.channel= channel; this.pis=pis; this._dst=_dst; this.monitor=monitor; this.mode=mode; }