public void RunTest() { Console.WriteLine("文件传输"); sshCp.Connect(); string localPath = @"F:\file\Code\SharpSSH-1.1.1.13.src"; string serverPath = @"/usr/lijie"; FileInfo[] distFIles = FileService.GetAllFiles(localPath); if (distFIles == null) { Console.WriteLine("没有发现更新文件"); //exec.Close(); sshCp.Close(); } Console.WriteLine("开始更新"); foreach (FileInfo tempFileInfo in distFIles) { string tempNowPath = serverPath + tempFileInfo.DirectoryName.MyTrimStr(localPath, null).Replace(@"\", @"/") + @"/" + tempFileInfo.Name; try { sshCp.Put(tempFileInfo.DirectoryName + @"\" + tempFileInfo.Name, tempNowPath); } catch (Exception ex) { Console.WriteLine(ex.Message); //scp: /tmp/dist/123: No such file or directory if (ex.Message.Contains("No such file or directory")) { string tempPath = ex.Message; tempPath = tempPath.Remove(0, tempPath.IndexOf(@"/")); tempPath = tempPath.Remove(tempPath.LastIndexOf(@"/")); Console.WriteLine("创建文件夹" + tempPath); if (MySshTool.SshFileMkFullDir(sshCp, tempPath)) { try { sshCp.Put(tempFileInfo.DirectoryName + @"\" + tempFileInfo.Name, tempNowPath); } catch (Exception innerEx) { Console.WriteLine(innerEx.Message); Console.WriteLine("传输失败,跳过该文件"); } } else { Console.WriteLine("创建文件夹失败,跳过该文件"); } } } } Console.WriteLine("更新完成"); sshCp.Close(); }
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 StartTransferBG() { try { DisableButtons(); sshT.Put(LocalFile, RemoteFile); } catch (Exception ex) { Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, Language.strSSHStartTransferBG + Environment.NewLine + ex.Message, true); } }
internal bool Put(string p1, string p2) { if (System.IO.File.Exists(p1)) { sshCp.Put(p1, p2); return(true);//在put执行完毕后,执行这个返回 } else { Log.warn(p1 + " 文件不存在"); return(false); } }
public void CopyFilesToRemote(List <FileInfo> files, string remotePath) { _sshCp.Connect(); int i = 0; StatusModel.Instance.Status = "Copying files"; foreach (FileInfo file in files) { _sshCp.Put(file.FullName, Path.Combine(remotePath, file.Name)); i++; StatusModel.Instance.setProgress(i, files.Count); } _sshCp.Close(); }
private static void UploadDirectory(string dirPath, string uploadPath) { string[] files = Directory.GetFiles(dirPath, "*.*"); string[] subDirs = Directory.GetDirectories(dirPath); foreach (string file in files) { sftpBase.Put(file, uploadPath + "/" + Path.GetFileName(file)); } foreach (string subDir in subDirs) { ssh.RunCommand("mkdir " + uploadPath + "/\"" + Path.GetFileName(subDir) + "\""); UploadDirectory(subDir, uploadPath + "/" + Path.GetFileName(subDir)); } }
private static void UpdateTripThruGatewayConfiguration() { ssh.RunCommand("rm " + remoteFilePath + "ServiceStack.TripThruGateway/Web/HostConfig.txt"); var configuration = JsonSerializer.DeserializeFromString <HostConfiguration>( File.ReadAllText("TripThruGatewayConfigurations/HostConfig.txt")); configuration.debug = env.debug; string configStr = JsonSerializer.SerializeToString <HostConfiguration>(configuration); File.WriteAllText("TripThruGatewayConfigurations/HostConfig.txt", configStr); sftpBase.Put("TripThruGatewayConfigurations/HostConfig.txt", remoteFilePath + "ServiceStack.TripThruGateway/Web/HostConfig.txt"); }
public bool Upload(string localPath, string remotePath) { try { if (!m_sshCp.Connected) { m_sshCp.Connect(); } m_sshCp.Put(localPath, remotePath); return(true); } catch { return(false); } }
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("文件传送失败"); } }
public bool Upload(string localPath, string remotePath) { try { if (!m_sshCp.Connected) { m_sshCp.Connect(); } m_sshCp.Put(localPath, remotePath); return(true); } catch (Exception ex) { Console.WriteLine("upload" + ex.Message); return(false); } }
private static void UpdateTripThruGatewayConfiguration() { ssh.RunCommand("rm " + remoteFilePath + "ServiceStack.TripThruGateway/Web/HostConfig.txt"); sftpBase.Put("TripThruGatewayConfigurations/HostConfig.txt", remoteFilePath + "ServiceStack.TripThruGateway/Web/HostConfig.txt"); }
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(); }
public void syncFile() { sshCp.Put(localFile, remoteFolder); }
/// <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); }