public static bool SshFileMkFullDir(SshTransferProtocolBase sshCp, string FilePath) { string[] files = FilePath.Split('/'); List <string> nowFileList = files.ToList <string>(); List <string> nextFileList = new List <string>(); string outErrMes = null; if (files.Length < 2) { return(false); } while (!SshFileMkDir(sshCp, StringHelper.StrListAdd(nowFileList, @"/"), out outErrMes)) { if (outErrMes.Contains("No such file or directory")) { nextFileList.Add(nowFileList[nowFileList.Count - 1]); nowFileList.RemoveAt(nowFileList.Count - 1); } else { return(false); } } for (int i = nextFileList.Count - 1; i >= 0; i--) { nowFileList.Add(nextFileList[i]); if (!SshFileMkDir(sshCp, StringHelper.StrListAdd(nowFileList, @"/"), out outErrMes)) { return(false); } } return(true); }
private void UploadFile() { try { //sshCp = new Sftp(Host.address, Host.Connection.Username); sshCp = new Scp(Host.address, Host.Connection.Username); sshCp.Password = Host.Connection.Password; sshCp.OnTransferProgress += new FileTransferEvent(sshCp_OnTransferProgress); sshCp.OnTransferEnd += new FileTransferEvent(sshCp_OnTransferEnd); log.InfoFormat("sshCp Connecting..."); sshCp.Connect(); log.InfoFormat("sshCp Connecting OK ......."); sshCp.Put(fromfile, outFolder + "/" + Path.GetFileName(fromfile)); isoUploadState = UploadState.InProgress; sshCp.Close(); } catch (Exception e) { log.Error(e); throw new Exception(Messages.UPLOAD_ISO_FAILED); } }
private void UploadFile(string fname) { SshTransferProtocolBase sshCp = null; if (ProgramSettings.settings.SshKey.Length == 0) { sshCp = new Scp(ProgramSettings.settings.SshHost, ProgramSettings.settings.SshLogin, ProgramSettings.settings.SshPass); } else { try { sshCp = new Scp(ProgramSettings.settings.SshHost, ProgramSettings.settings.SshLogin); if (ProgramSettings.settings.SshPass.Length == 0) { sshCp.AddIdentityFile(ProgramSettings.settings.SshKey); } else { sshCp.AddIdentityFile(ProgramSettings.settings.SshKey, ProgramSettings.settings.SshPass); } } catch {} } sshCp.Connect(ProgramSettings.settings.SshPort); sshCp.Put(fname, ProgramSettings.settings.LstDir + "/" + fname); sshCp.Close(); return; }
//host:sftp地址 user:用户名 pwd:密码 /// <summary> /// 执行文件的get 和put /// 对于删除和查询操作,使用shellhelp /// </summary> /// <param name="host"></param> /// <param name="user"></param> /// <param name="pwd"></param> public SFTPHelper(string host, string user, string pwd) { string[] arr = host.Split(':'); string ip = arr[0];//端口指定 在 int port = 22; if (arr.Length > 1) { port = Int32.Parse(arr[1]); } if (host.Equals("scp")) { sshCp = new Scp(ip, user); } else { sshCp = new Tamir.SharpSsh.Sftp(ip, user); } if (pwd != null) { sshCp.Password = pwd; } // if (input.IdentityFile != null) sshCp.AddIdentityFile(input.IdentityFile); sshCp.OnTransferStart += new FileTransferEvent(sshCp_OnTransferStart); sshCp.OnTransferProgress += new FileTransferEvent(sshCp_OnTransferProgress); sshCp.OnTransferEnd += new FileTransferEvent(sshCp_OnTransferEnd); Console.Write("Connecting..."); }
public OneWayFileSyncSSH(string host, string user, string password, string localFile, string remoteFolder) { this.localFile = localFile; this.remoteFolder = remoteFolder; sshCp = new Tamir.SharpSsh.Sftp(host, user); sshCp.Password = password; sshCp.Connect(); }
public OneWayFolderSyncSSH(SshExec exec, SshTransferProtocolBase sshCp, string localFolder, string remoteFolder) { this.localFolder = localFolder; this.remoteFolder = remoteFolder; this.localFiles = new ArrayList(); this.remoteFiles = new ArrayList(); this.exec = exec; this.sshCp = sshCp; }
public SFTPHelper() { // //TODO: Check connectionInfo // m_sshCp = new Sftp(sinapay_config.Sftp_Host, sinapay_config.Sftp_User); if (sinapay_config.Sftp_IdentityFile != null) { m_sshCp.AddIdentityFile(sinapay_config.Sftp_IdentityFile); } }
private static void OpenSshConnection() { ssh = new SshExec(host, user, password); ssh.Connect(sshPort); Console.WriteLine("Connected"); sftpBase = new Tamir.SharpSsh.Sftp(host, user, password); sftpBase.OnTransferStart += new FileTransferEvent(sftpBase_OnTransferStart); sftpBase.OnTransferEnd += new FileTransferEvent(sftpBase_OnTransferEnd); Console.WriteLine("Trying to Open Connection..."); sftpBase.Connect(sshPort); Console.WriteLine("Connected Successfully !"); }
public SFTPHelper(SshConnectionInfo connectionInfo) { m_sshCp = new Sftp(connectionInfo.Host, connectionInfo.User); if (connectionInfo.Pass != null) { m_sshCp.Password = connectionInfo.Pass; } if (connectionInfo.IdentityFile != null) { m_sshCp.AddIdentityFile(connectionInfo.IdentityFile); } }
public static bool SshFileMkDir(SshTransferProtocolBase sshCp, string FilePath, out string errMes) { errMes = null; try { sshCp.Mkdir(FilePath); return(true); } catch (Exception ex) { errMes = ex.Message; return(false); } }
public OneWayFolderSyncSSH(string host, string user, string password, string localFolder, string remoteFolder) { this.localFolder = localFolder; this.remoteFolder = remoteFolder; this.localFiles = new ArrayList(); this.remoteFiles = new ArrayList(); exec = new SshExec(host, user); sshCp = new Tamir.SharpSsh.Sftp(host, user); exec.Password = password; sshCp.Password = password; exec.Connect(); sshCp.Connect(); }
/// <summary> /// move all file to remote Asyn (使用异步的方式将指定文件夹内的所有文件包括之目录的所有文件在保留目录结果的提前向下复制到shh服务器的指定目录) /// </summary> /// <param name="sshCp">ssh</param> /// <param name="LocalFilePath">Local File Path</param> /// <param name="remoteFilePath">remote File Path</param> /// <param name="reportProcess">report Process </param> /// <param name="reportError">report Error</param> /// <returns>is creat task success</returns> public static bool SshMvAllFileAsyn(SshTransferProtocolBase sshCp, string LocalFilePath, string remoteFilePath, Action <string> reportProcess, Action <string> reportError) { string outError = null; if (!sshCp.Connected) { return(false); } ParameterizedThreadStart fileMvTask = new ParameterizedThreadStart((args) => { SshMvAllFileSync((SshTransferProtocolBase)((object[])args)[0], (string)((object[])args)[1], (string)((object[])args)[2], out outError, (Action <string>)((object[])args)[3], (Action <string>)((object[])args)[4]); }); Thread mySshFileMvThread = new Thread(fileMvTask); mySshFileMvThread.Name = "SshMvAllFileAsynWithSshTransferProtocolBase"; mySshFileMvThread.Priority = ThreadPriority.Normal; mySshFileMvThread.IsBackground = true; mySshFileMvThread.Start(new object[] { sshCp, LocalFilePath, remoteFilePath, reportProcess, reportError }); return(true); }
private void send_Click_1(object sender, EventArgs e) { Host = this.IP.Text; User = this.userName.Text; Pass = this.password.Text; IdentityFile = this.targetPath.Text; if (!type && !checkDir(IdentityFile)) { MessageBox.Show("路径格式错误"); return; } Util.SshConnectionInfo input = Util.GetConnectionInfo(Host, User, Pass, IdentityFile); sshCp = new Scp(input.Host, input.User); sshCp.Password = input.Pass; try { sshCp.Connect(); MessageBox.Show("连接主机成功"); } catch { MessageBox.Show("连接主机失败"); return; } try { if (type) { sshCp.Get(this.targetPath.Text, this.sourcePath.Text); // sshCp.Put(this.sourcePath.Text, handleDir(this.sourcePath.Text, this.targetPath.Text)); MessageBox.Show("下载成功"); } else { sshCp.Put(this.sourcePath.Text, handleDir(this.sourcePath.Text, this.targetPath.Text)); MessageBox.Show("上传成功"); } } catch { MessageBox.Show("文件传送失败"); } }
private void StartTransfer(SSHTransferProtocol Protocol) { if (AllFieldsSet() == false) { Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, Language.strPleaseFillAllFields); return; } if (File.Exists(txtLocalFile.Text) == false) { Runtime.MessageCollector.AddMessage(Messages.MessageClass.WarningMsg, Language.strLocalFileDoesNotExist); return; } try { if (Protocol == SSHTransferProtocol.SCP) { sshT = new Scp(txtHost.Text, txtUser.Text, txtPassword.Text); } else if (Protocol == SSHTransferProtocol.SFTP) { sshT = new Sftp(txtHost.Text, txtUser.Text, txtPassword.Text); } sshT.OnTransferStart += SshTransfer_Start; sshT.OnTransferProgress += SshTransfer_Progress; sshT.OnTransferEnd += SshTransfer_End; sshT.Connect(Convert.ToInt32(txtPort.Text)); LocalFile = txtLocalFile.Text; RemoteFile = txtRemoteFile.Text; Thread t = new Thread(new ThreadStart(StartTransferBG)); t.SetApartmentState(ApartmentState.STA); t.IsBackground = true; t.Start(); } catch (Exception ex) { Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, Language.strSSHTransferFailed + Environment.NewLine + ex.Message); sshT.Close(); } }
public static bool InitSSH() { bool yes = false; if (LoadSettings()) { SshExec exec = new SshExec(SshSettings.server, SshSettings.user); sshexec = exec; SshTransferProtocolBase sshCp = new Scp(SshSettings.server, SshSettings.user); //А можно и так //sshCp = new Sftp(input.Host, input.User); sshsess = sshCp; yes = true; } else { yes = false; } return(yes); }
public SSHManager(string host, string username, string password) { _shell = new SshShell(host, username, password); _exec = new SshExec(host, username, password); _sshCp = new Scp(host, username, password); }
private static void Main(string[] args) { var env = environments["vagrant"]; var localPath = "Z:\\WindowsDev\\Gateway\\"; var remoteFilePath = "/home/tripservice/servicestack/"; var host = env.host; var user = env.user; var password = env.password; var sshPort = env.sshPort; var monoServer = "http://" + host + "/"; var webServer = "http://" + host + ":8080/"; ssh = new SshExec(host, user, password); ssh.Connect(sshPort); Console.WriteLine("Connected"); sftpBase = new Tamir.SharpSsh.Sftp(host, user, password); sftpBase.OnTransferStart += new FileTransferEvent(sftpBase_OnTransferStart); sftpBase.OnTransferEnd += new FileTransferEvent(sftpBase_OnTransferEnd); Console.WriteLine("Trying to Open Connection..."); sftpBase.Connect(sshPort); Console.WriteLine("Connected Successfully !"); if (fullDeploy) { //Remove any old files and upload projects Console.WriteLine("Uploading projects"); ssh.RunCommand("cd " + remoteFilePath); ssh.RunCommand("rm -rf " + remoteFilePath + "ServiceStack.* Booking*"); ssh.RunCommand("mkdir -p " + remoteFilePath + "ServiceStack.TripThruGateway/Web"); ssh.RunCommand("mkdir -p " + remoteFilePath + "ServiceStack.TripThruPartnerGateway/Web"); ssh.RunCommand("mkdir -p " + remoteFilePath + "BookingWebsite"); var omittedDirectories = new List <string> { "packages" }; UploadDirectory(localPath + "BookingWebsite", remoteFilePath + "BookingWebsite"); UploadDirectory(localPath + "ServiceStack.TripThruGateway/Web", remoteFilePath + "ServiceStack.TripThruGateway/Web"); UploadDirectory(localPath + "ServiceStack.TripThruPartnerGateway/Web", remoteFilePath + "ServiceStack.TripThruPartnerGateway/Web"); ssh.RunCommand("mv " + remoteFilePath + "ServiceStack.TripThruGateway/Web/mono/* " + remoteFilePath + "ServiceStack.TripThruGateway/Web/bin"); ssh.RunCommand("mv " + remoteFilePath + "ServiceStack.TripThruPartnerGateway/Web/mono/* " + remoteFilePath + "ServiceStack.TripThruPartnerGateway/Web/bin"); } var webappNames = new List <string>(); string[] partnerConfigurations = Directory.GetFiles("PartnerConfigurations/", "*.txt"); List <string> partnerscallbackUrlMono = new List <string>(); foreach (var partnerConfiguration in partnerConfigurations) { var configuration = JsonSerializer.DeserializeFromString <PartnerConfiguration>(File.ReadAllText(partnerConfiguration)); configuration.TripThruUrlMono = monoServer + configuration.TripThruUrlMono; configuration.Partner.CallbackUrlMono = monoServer + configuration.Partner.CallbackUrlMono; configuration.Partner.WebUrl = webServer + configuration.Partner.WebUrl; string configStr = JsonSerializer.SerializeToString <PartnerConfiguration>(configuration); File.WriteAllText(partnerConfiguration, configStr); if (configuration.Enabled) { partnerscallbackUrlMono.Add(configuration.Partner.CallbackUrlMono); var name = configuration.Partner.Name.Replace(" ", ""); Console.WriteLine("Configuring " + name); webappNames.Add(name); ssh.RunCommand("cp -a " + remoteFilePath + "ServiceStack.TripThruPartnerGateway/ " + remoteFilePath + "ServiceStack." + name + "/"); ssh.RunCommand("rm " + remoteFilePath + "ServiceStack." + name + "/Web/PartnerConfiguration.txt"); sftpBase.Put(partnerConfiguration, remoteFilePath + "ServiceStack." + name + "/Web/PartnerConfiguration.txt"); var bookingwebConfig = new System.IO.StreamWriter("config.txt"); bookingwebConfig.WriteLine("HomeUrl=" + configuration.Partner.WebUrl); bookingwebConfig.WriteLine("RelativeHomeUrl=" + configuration.Partner.WebUrlRelative); bookingwebConfig.WriteLine("TripThruUrl=" + configuration.TripThruUrlMono); bookingwebConfig.WriteLine("TripThruAccessToken=" + "jaosid1201231"); //fixed tripthru access token bookingwebConfig.WriteLine("PartnerUrl=" + configuration.Partner.CallbackUrlMono); bookingwebConfig.WriteLine("PartnerAccessToken=" + configuration.Partner.AccessToken); bookingwebConfig.WriteLine("PartnerName=" + name); bookingwebConfig.WriteLine("PartnerId=" + configuration.Partner.ClientId); bookingwebConfig.Flush(); bookingwebConfig.Close(); ssh.RunCommand("rm " + remoteFilePath + "BookingWebsite/inc/tripthru/config.txt"); sftpBase.Put("config.txt", remoteFilePath + "BookingWebsite/inc/tripthru/"); ssh.RunCommand("rm " + remoteFilePath + "BookingWebsite/images/taxi-cars_logo.png"); var x = name + ".png"; var y = remoteFilePath + "BookingWebsite/images/taxi-cars_logo.png"; sftpBase.Put("PartnerConfigurations/" + name + ".png", remoteFilePath + "BookingWebsite/images/taxi-cars_logo.png"); ssh.RunCommand("rm -rf /var/www/sanfran/Bookings" + name); ssh.RunCommand("cp -a " + remoteFilePath + "BookingWebsite/ /var/www/sanfran/Bookings" + name); } } if (fullDeploy) { //create fast-cgi mono webapp config var webappConfig = new System.IO.StreamWriter("tripthru.webapp"); webappConfig.WriteLine("<apps>"); webappConfig.Flush(); webappConfig.WriteLine(@"<web-application> <name>TripThru.TripThruGateway</name> <vhost>*</vhost> <vport>80</vport> <vpath>/TripThru.TripThruGateway</vpath> <path>/var/www/ServiceStack.TripThruGateway/Web</path> </web-application>" ); webappConfig.Flush(); foreach (var webapp in webappNames) { webappConfig.WriteLine(@"<web-application> <name>TripThru.{0}</name> <vhost>*</vhost> <vport>80</vport> <vpath>/TripThru.{0}</vpath> <path>/var/www/ServiceStack.{0}/Web</path> </web-application>", webapp ); webappConfig.Flush(); } webappConfig.WriteLine("</apps>"); webappConfig.Flush(); webappConfig.Close(); Console.WriteLine("Updating mono webapp config"); ssh.RunCommand("rm /etc/rc.d/init.d/mono-fastcgi/tripthru.webapp"); sftpBase.Put("tripthru.webapp", "/etc/rc.d/init.d/mono-fastcgi/tripthru.webapp"); } Console.WriteLine("Stopping mono"); ssh.RunCommand("kill -9 $(netstat -tpan |grep \"LISTEN\"|grep :9000|awk -F' ' '{print $7}'|awk -F'/' '{print $1}')"); Console.WriteLine("Updating web folder"); ssh.RunCommand("rm -rf /var/www/ServiceStack.*"); ssh.RunCommand("cp -a " + remoteFilePath + "/ServiceStack.* /var/www/"); Thread startMono = new Thread( delegate() { Console.WriteLine("Starting mono"); ssh.RunCommand("export MONO_OPTIONS=\"--debug\""); ssh.RunCommand("fastcgi-mono-server4 --appconfigdir /etc/rc.d/init.d/mono-fastcgi /socket=tcp:127.0.0.1:9000 /logfile=/var/log/mono/fastcgi.log &"); }); startMono.Start(); Console.WriteLine("Sleep 8 seconds, waiting for mono to initialize."); Thread.Sleep(8000); var client = new System.Net.WebClient(); foreach (string callbackUrlMono in partnerscallbackUrlMono) { Console.WriteLine("Sending request to: \n" + @callbackUrlMono.ToString() + "log"); while (true) { try { var response = client.DownloadString(@callbackUrlMono.ToString() + "log"); var analyzeResponse = JsonSerializer.DeserializeFromString <ResponseRequest>(response); if (analyzeResponse.ResultCode.Equals("OK")) { Console.WriteLine("Correct."); break; } else { Thread.Sleep(1000); } } catch (Exception ex) { } } } Console.WriteLine("Done!"); startMono.Abort(); sftpBase.Close(); ssh.Close(); }
/// <summary> /// move all file to remote Sync (使用同步的方式将指定文件夹内的所有文件包括之目录的所有文件在保留目录结果的提前向下复制到shh服务器的指定目录) /// </summary> /// <param name="sshCp"></param> /// <param name="LocalFilePath">Local File Path</param> /// <param name="remoteFilePath">remote File Path</param> /// <param name="errMes"></param> /// <param name="reportProcess">report Process </param> /// <param name="reportError">report Error</param> /// <returns></returns> public static bool SshMvAllFileSync(SshTransferProtocolBase sshCp, string LocalFilePath, string remoteFilePath, out string errMes, Action <string> reportProcess, Action <string> reportError) { errMes = null; bool outResult = true; var PutOutReport = new Action <string>((str) => { if (reportProcess != null) { reportProcess(str); } }); var PutOutError = new Action <string>((str) => { if (reportProcess != null) { reportError(str); } }); FileTransferEvent fileTransferStart = new FileTransferEvent((src, dst, transferredBytes, totalBytes, message) => PutOutReport(string.Format("Put file {0} to {1} state:{2}", src, dst, message))); FileTransferEvent fileTransferEnd = new FileTransferEvent((src, dst, transferredBytes, totalBytes, message) => PutOutReport(string.Format("Put file {0} to {1} state:{2}", src, dst, message))); if (!sshCp.Connected) { errMes = "SshTransferProtocolBase not Connected"; PutOutError(errMes); return(false); } FileInfo[] distFIles = FileService.GetAllFiles(LocalFilePath); if (distFIles == null) { errMes = "no file in LocalFilePath"; PutOutError(errMes); return(false); } sshCp.OnTransferStart += fileTransferStart; sshCp.OnTransferEnd += fileTransferEnd; PutOutReport("start Mv"); foreach (FileInfo tempFileInfo in distFIles) { string tempNowPath = remoteFilePath + tempFileInfo.DirectoryName.MyTrimStr(LocalFilePath, null).Replace(@"\", @"/") + @"/" + tempFileInfo.Name; try { sshCp.Put(tempFileInfo.DirectoryName + @"\" + tempFileInfo.Name, tempNowPath); } catch (Exception ex) { PutOutReport(ex.Message); if (ex.Message.Contains("No such file or directory")) { string tempPath = ex.Message; tempPath = tempPath.Remove(0, tempPath.IndexOf(@"/")); tempPath = tempPath.Remove(tempPath.LastIndexOf(@"/")); PutOutReport("Create folder" + tempPath); if (MySshTool.SshFileMkFullDir(sshCp, tempPath)) { try { sshCp.Put(tempFileInfo.DirectoryName + @"\" + tempFileInfo.Name, tempNowPath); } catch (Exception innerEx) { PutOutError(innerEx.Message); PutOutError(string.Format("transfer fail ,skip this file [from {0} to {1}]", tempFileInfo.DirectoryName + @"\" + tempFileInfo.Name, tempNowPath)); outResult = false; } } else { PutOutError(string.Format("create folder Failed,skip this folder [{0}]", tempPath)); outResult = false; } } } } PutOutReport("Mv Complete"); sshCp.OnTransferStart -= fileTransferStart; sshCp.OnTransferEnd -= fileTransferEnd; return(outResult); }
public OneWayFileSyncSSH(SshTransferProtocolBase sshCp, string localFile, string remoteFolder) { this.localFile = localFile; this.remoteFolder = remoteFolder; this.sshCp = sshCp; }