static void Main(string[] args) { Sftp sftp = new Sftp("[SERVER]", "[USERNAME]", string.Empty); sftp.AddIdentityFile("[Path to Private kEY]"); sftp.Connect(); sftp.Put(@"D:\temp\blog\feed.csv", "[PATH OF FILE ON SERVER]"); sftp.Delete("[PATH OF FILE ON SERVER]"); }
public bool SftpFile( string fileName ) { SshTransferProtocolBase sshCp = new Sftp( m_sftpSite, m_sftpSiteUserName ); sshCp.Password = m_sftpSitePassword; sshCp.OnTransferStart += new FileTransferEvent(sshCp_OnTransferStart); sshCp.OnTransferProgress += new FileTransferEvent(sshCp_OnTransferProgress); sshCp.OnTransferEnd += new FileTransferEvent(sshCp_OnTransferEnd); // string lfile = @"d:\apps\logs\ReadWriteMgrLog.log"; string rfile = ParseFileName(fileName); string remoteFileName = m_sftpSiteRemoteFolder + rfile; sshCp.Connect(); try { sshCp.Put(fileName, remoteFileName); } catch (Tamir.SharpSsh.jsch.SftpException e) { LogMsg("SftpHandler::SftpFile():ECaught:UnableToCreateEventLogFile::" + e.Message + e.InnerException); return false; } catch (Tamir.SharpSsh.SshTransferException e) { LogMsg("SftpHandler::SftpFile():ECaught:UnableToCreateEventLogFile::" + e.Message + e.InnerException); return false; } catch (SystemException se) { LogMsg("SftpHandler::SftpFile():ECaught:UnableToCreateEventLogFile::" + se.Message); return false; } return true; }
public bool AddFile(int jobId, byte[] fileData, string filename) { if(filename.Contains("/")) return false; //fail for securety //if (filename.Contains(' ')) return false; //fail for securety string dir = string.Format(@"{0}{1}", tempDir, filename); Sftp sftp = new Sftp(HostName, UserName,Password); sftp.Connect(); File.WriteAllBytes(dir, (byte[]) fileData); sftp.Put(dir,string.Format("{2}{1}/{0}", filename, jobId.ToString(),DataPath)); File.Delete(dir); return true; }
public void APN(int storyid, string p_headline, string p_story) { // check to see if the APN feed is active // if Yes, create the NewsML record and send it out string m_headline = p_headline; string m_story = p_story; string m_active = ""; String connectionString = ConfigurationManager.ConnectionStrings["azureConnectionString"].ConnectionString; try { // Connect to the database and run the query. SqlConnection con = new SqlConnection(connectionString); string strSQL = "Select active from customermessage where customerid = '2' and active = 'Y'"; SqlCommand cmd = new SqlCommand(strSQL, con); cmd.CommandType = CommandType.Text; con.Open(); SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { m_active = (dr["active"].ToString()); TimeZoneInfo timeZoneInfo; //Set the time zone information to New Zealand Standard Time timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("New Zealand Standard Time"); //Get date and time in New Zealand Standard Time var m_nzdate = TimeZoneInfo.ConvertTimeFromUtc(System.DateTime.UtcNow, timeZoneInfo); XmlWriter writer = null; var m_id = Convert.ToString(storyid); //Trace.WriteLine("Processing Story ID: " + m_id); string file_now = m_nzdate.ToString("yyyMMddHHmmss") + "-" + m_id + ".XML"; //LocalResource myStorage = RoleEnvironment.GetLocalResource("XMLStorage"); string pathToFiles = Server.MapPath("/Stories/"); string filepath = Path.Combine(pathToFiles, file_now); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; // write the NewsML file for APN, writer = XmlWriter.Create(filepath, settings); string x_story = ReplaceWordChars(m_story); m_story = x_story; string[] lines = m_story.Replace("\r", "").Split('\n'); string m_embargoed = string.Empty; m_headline = m_headline.Replace("\r", string.Empty); //var m_reporter = lines[0]; var m_reporter = "Staff Reporter"; //if (m_reporter.Length > 3) //{ // m_reporter = m_reporter.Substring(3, m_reporter.Length - 3); //} //else //{ // m_reporter = "Staff Reporter"; //} // write the NewsML file for APN, IRG writer.WriteComment("BusinessDesk NewsML"); writer.WriteStartElement("newsMessage", "http://iptc.org/std/nar/2006-10-01/"); writer.WriteAttributeString("xsi", "schemaLocation", "http://iptc.org/std/nar/2006-10-01/", "http://www.iptc.org/std/NAR/1.9/specification/NewsML-G2_2.8-spec-NewsItem-Power.xsd"); writer.WriteAttributeString("standard", "NewsML-G2"); writer.WriteAttributeString("standardversion", "2.8"); writer.WriteAttributeString("conformance", "power"); writer.WriteAttributeString("lang", "en-US"); // START Header writer.WriteStartElement("Header"); writer.WriteStartElement("Sent"); writer.WriteString(m_nzdate.ToString("yyyy-MM-dd HH:mm:ss")); writer.WriteEndElement(); writer.WriteStartElement("sender"); writer.WriteString("BusinessDesk"); writer.WriteEndElement(); writer.WriteStartElement("origin"); writer.WriteString("BusinessDesk"); writer.WriteEndElement(); writer.WriteStartElement("transmitId"); writer.WriteString(m_nzdate.ToString("yyyMMddHHmmss")); writer.WriteEndElement(); writer.WriteStartElement("priority"); writer.WriteString("5"); writer.WriteEndElement(); writer.WriteStartElement("destination"); writer.WriteString("All"); writer.WriteEndElement(); writer.WriteEndElement(); // END Header // // START ItemSet writer.WriteStartElement("itemSet"); // START Package Item writer.WriteStartElement("packageItem"); writer.WriteStartElement("itemRef"); writer.WriteAttributeString("residref", m_nzdate.ToString("yyyMMddHHmmss")); writer.WriteEndElement(); writer.WriteEndElement(); // END PackageItem // // START NewsItem writer.WriteStartElement("newsItem"); writer.WriteAttributeString("guid", "BD-" + m_nzdate.ToString("yyyMMddHHmmss")); writer.WriteAttributeString("version", "3"); writer.WriteAttributeString("standard", "NewsML-G2"); writer.WriteAttributeString("standardversion", "2.7"); writer.WriteStartElement("catalogRef"); writer.WriteAttributeString("href", "http://www.iptc.org/std/catalog/catalog.IPTC-G2-Standards_13.xml"); writer.WriteEndElement(); // START RightsInfo writer.WriteStartElement("rightsInfo"); writer.WriteStartElement("copyrightHolder"); writer.WriteAttributeString("literal", ""); writer.WriteEndElement(); writer.WriteStartElement("copyrightNotice"); writer.WriteEndElement(); writer.WriteEndElement(); // END RightsInfo // // START ItemMeta writer.WriteStartElement("itemMeta"); writer.WriteStartElement("itemClass"); writer.WriteAttributeString("qcode", "ninat:text"); writer.WriteEndElement(); writer.WriteStartElement("provider"); writer.WriteAttributeString("literal", "CL"); writer.WriteEndElement(); writer.WriteStartElement("versionCreated"); writer.WriteString(m_nzdate.ToString("yyyMMddHHmmss")); writer.WriteEndElement(); writer.WriteStartElement("embargoed"); writer.WriteString(m_embargoed); writer.WriteEndElement(); writer.WriteStartElement("ednote"); writer.WriteString(""); writer.WriteEndElement(); writer.WriteStartElement("pubStatus"); writer.WriteAttributeString("qcode", "stat:usable"); writer.WriteEndElement(); writer.WriteEndElement(); // END ItemMeta // // START ContentMeta writer.WriteStartElement("contentMeta"); writer.WriteStartElement("urgency"); writer.WriteString("5"); writer.WriteEndElement(); writer.WriteStartElement("keyword"); writer.WriteAttributeString("role", "krole:index"); writer.WriteString(""); writer.WriteEndElement(); // Taxonomy field value string smarket = ""; string mqcode = "type"; writer.WriteStartElement("subject"); writer.WriteAttributeString(mqcode, "Topic"); writer.WriteStartElement("name"); writer.WriteString(smarket); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndElement(); // END COntentMeta // // START COntentSet writer.WriteStartElement("contentSet"); // START INLINEXML writer.WriteStartElement("inlineXML"); writer.WriteAttributeString("contenttype", "application/nitf+xml"); writer.WriteStartElement("nitf"); //writer.WriteAttributeString("xmlns", "http://iptc.org/std/NITF/2006-10-18/"); writer.WriteAttributeString("xsi", "schemaLocation", "http://iptc.org/std/NITF/2006-10-18/", "http://www.iptc.org/std/NITF/3.5/specification/nitf-3-5.xsd"); // HEAD writer.WriteStartElement("head"); writer.WriteStartElement("title"); writer.WriteString(m_headline); writer.WriteEndElement(); writer.WriteEndElement(); // END HEAD // // START BODY writer.WriteStartElement("body"); // START BODY Head writer.WriteStartElement("body.head"); writer.WriteStartElement("byline"); writer.WriteString("By"); writer.WriteStartElement("person"); writer.WriteString(m_reporter); writer.WriteEndElement(); writer.WriteStartElement("byttl"); writer.WriteString("BusinessDesk"); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteStartElement("abstract"); writer.WriteString(" "); writer.WriteEndElement(); writer.WriteEndElement(); //END Body Head // // START Body Content writer.WriteStartElement("body.content"); foreach (string str in lines) { if (str.Length > 1) { writer.WriteStartElement("p"); writer.WriteString(str.Trim()); writer.WriteEndElement(); } } writer.WriteEndElement(); // END Body Content writer.WriteEndElement(); //END BODY writer.WriteEndElement(); // END NITF writer.WriteEndElement(); // END INLINEXML writer.WriteEndElement(); // END CONTENTSET writer.WriteEndElement(); // END NewsItem writer.WriteEndElement(); // END ItemSet writer.WriteEndElement(); // END NewsMessage writer.Flush(); writer.Close(); // try { // // now send to APN // SshTransferProtocolBase sshCpAPN; sshCpAPN = new Sftp("ftp1.apnz.co.nz", "ContentLtd"); sshCpAPN.Password = "******"; sshCpAPN.Connect(); string lfile = filepath; string rfile = "/incoming/" + file_now; sshCpAPN.Put(lfile, rfile); sshCpAPN.Close(); //Trace.WriteLine(m_id, "APN - Success"); } catch (Exception ex) { //Trace.WriteLine(m_id, "APN - Fail"); } } cmd.Dispose(); con.Close(); con.Dispose(); } catch (Exception) { } }
protected void APN_Send(int msgid, string m_ftp_host, string m_ftp_username, string m_ftp_password, string m_sftp_path, string m_messagename) { var m_headline = ""; string m_customer = "APN"; var m_msgid = msgid.ToString(); String connectionString = ConfigurationManager.ConnectionStrings["azureConnectionString"].ConnectionString; try { // Connect to the database and run the query. SqlConnection con = new SqlConnection(connectionString); string strSQL = "Select headline from story where storyid = " + msgid; SqlCommand cmd = new SqlCommand(strSQL, con); cmd.CommandType = CommandType.Text; con.Open(); SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { m_headline = (dr["headline"].ToString()); } cmd.Dispose(); con.Close(); con.Dispose(); } catch (Exception ex) { // The connection failed. Display an error message. PublishLog(m_msgid, m_headline, m_customer, ex.Message, "Pub Error"); } //PublishLog(m_msgid, m_headline, m_customer, "APN Step 1", "Publish OK"); string m_msg_file = m_msgid + ".xml"; string m_fileroot = "http://businessdesk.blob.core.windows.net/messages/"; string m_file = m_fileroot + m_msg_file; CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=businessdesk;AccountKey=zWYFxlr7zhbMhXLptJ2lvtrORvoPTVunsDAf/v8B0tDsUWMigwFOJs9wEZ62XU6UdFWM1BQJ/SN9dZ0JsWVlpw=="); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("messages"); CloudBlockBlob blockBlob = container.GetBlockBlobReference(m_msg_file); string pathToFiles = Server.MapPath("/Stories/"); string m_File = pathToFiles + m_msg_file; //PublishLog(m_msgid, m_headline, m_customer, "APN Step 2", "Publish OK"); try { using (var fileStream = File.OpenWrite(m_File)) { blockBlob.DownloadToStream(fileStream); } } catch (Exception ex) { PublishLog(m_msgid, m_headline, m_customer, ex.Message, "Pub Error"); } try { SshTransferProtocolBase sshCpAPN; sshCpAPN = new Sftp("ftp1.apnz.co.nz", "ContentLtd"); sshCpAPN.Password = "******"; sshCpAPN.Connect(); string lfile = m_File; string rfile = "/incoming/" + m_msg_file; sshCpAPN.Put(lfile, rfile); sshCpAPN.Close(); PublishLog(m_msgid, m_headline, m_customer, "APN SFTP Pub OK", "Publish OK"); } catch (WebException ex) { PublishLog(m_msgid, m_headline, m_customer, ex.Message, "Pub Error"); } }
private void button1_Click(object sender, EventArgs e) { string makefile = HKLibrary.UTIL.HKFileHelper.GetCurrentDirectory(); string sDirPath; sDirPath = makefile + "\\data"; DirectoryInfo di = new DirectoryInfo(sDirPath); if (di.Exists == false) { di.Create(); } string PinCode = "41302903000002"; makefile = makefile + "\\data\\" + PinCode + ".png"; Int32 OrderSeq = 406359; string folderName = Convert.ToString(OrderSeq); string ftpfileName = folderName + "/" + PinCode + ".jpg"; string ftpBasicPath = "/var/www/IMAGE/Web/upload/order/barcode"; //string ftpBasicPath = "/var/www/IMAGE/Web/upload/order/qrcode/"; QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M); QrCode qrCode = qrEncoder.Encode(PinCode); var renderer = new GraphicsRenderer(new FixedCodeSize(400, QuietZoneModules.Zero), Brushes.Black, Brushes.White); MemoryStream ms = new MemoryStream(); renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, ms); var image = new Bitmap(Image.FromStream(ms), new Size(new Point(200, 200))); image.Save(makefile, ImageFormat.Png); Tamir.SharpSsh.Sftp sftp; sftp = new Tamir.SharpSsh.Sftp("ledev.leisureq.co.kr", "lion", "gkffl1!"); sftp.Connect(10004); ArrayList res = sftp.GetFileList("/"); sftp.Mkdir(ftpBasicPath + "/" + folderName + "/"); sftp.Put(makefile, ftpBasicPath + "/" + ftpfileName); sftp.Close(); //BarcodeLib.Barcode b = new BarcodeLib.Barcode(); //b.Encode(BarcodeLib.TYPE.CODE128, PinCode); //b.SaveImage(makefile, BarcodeLib.SaveTypes.JPG); /* * string date = "2015-05-20 17:16:44"; * string[] datePartPath = new string[4]; * * DateTime dt = Convert.ToDateTime(date); * datePartPath[0] = dt.ToString("yyyy"); * datePartPath[1] = dt.ToString("MM"); * datePartPath[2] = dt.ToString("dd"); * datePartPath[3] = Convert.ToString(OrderSeq); * * * for(Int32 i =0; i<datePartPath.Length; i++){ * ftpBasicPath = ftpBasicPath + "/" + datePartPath[i]; * } * comwls.image_01_FileMake(ftpBasicPath); * */ string ftpUri = "sftp://ledev.leisureq.co.kr:10004/" + ftpBasicPath + folderName; HKLibrary.comwls.comwls.image_01_FileMake(ftpBasicPath + folderName); FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUri); request.Method = WebRequestMethods.Ftp.MakeDirectory; //request.Method = WebRequestMethods.Ftp.UploadFile; // This example assumes the FTP site uses anonymous logon. request.Credentials = new NetworkCredential("lion", "gkffl1!"); FtpWebResponse response = (FtpWebResponse)request.GetResponse(); Stream ftpStream = response.GetResponseStream(); ftpStream.Close(); response.Close(); /* * string ftpUri = "ftp://121.78.127.40:21/" + ftpBasicPath + folderName; * * FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUri); * request.Method = WebRequestMethods.Ftp.MakeDirectory; * * // This example assumes the FTP site uses anonymous logon. * request.Credentials = new NetworkCredential("infobay", "info9887"); * FtpWebResponse response = (FtpWebResponse)request.GetResponse(); * Stream ftpStream = response.GetResponseStream(); * * ftpStream.Close(); * response.Close(); * * ftpUri = "ftp://121.78.127.40:21/" + ftpBasicPath + ftpfileName; * request = (FtpWebRequest)WebRequest.Create(ftpUri); * request.Method = WebRequestMethods.Ftp.UploadFile; * * // This example assumes the FTP site uses anonymous logon. * request.Credentials = new NetworkCredential("infobay", "info9887"); * * byte[] fileContents = File.ReadAllBytes(makefile); * request.ContentLength = fileContents.Length; * * request.UsePassive = true; * Stream requestStream = request.GetRequestStream(); * requestStream.Write(fileContents, 0, fileContents.Length); * requestStream.Close(); * response = (FtpWebResponse)request.GetResponse(); * response.Close(); * * * * //sftp.ConnectTimeoutMs = 15000; * //sftp.IdleTimeoutMs = 15000; * * //string hostname = "ftp://ledev.leisureq.co.kr:10004/"; * * //bool success = sftp.Connect(hostname, 10004); */ }
public string SubmitGenPhen(int jobId,string jobName,string treeName, string postBackURL) { Sftp sftp = new Sftp(HostName, UserName, Password); sftp.Connect(); string dir = string.Format(@"{0}GenPhenBatch.job", tempDir); using (StreamWriter writer = new StreamWriter(dir, false)) { writer.Write("#PBS -l walltime=03:00:00 \n#PBS -l nodes=1:ppn=1 \n"); writer.Write("#PBS -N GenPhen_" + jobId.ToString() + " \n#PBS -j oe \n"); writer.Write("#PBS -S /bin/ksh \n"); writer.Write("PATH=$PATH:"+PoyPath+" \n"); writer.Write(string.Format("cd {0}{1}/ \n", DataPath,jobId)); writer.Write("echo the start time is `date`\n"); writer.Write("mpiexec add_arbitrary_weights.awk "+treeName+" >temp_tree.tre\n"); writer.Write("cat temp_tree.tre "+jobName+".poy_output | mpiexec add_tree.pl >"+jobName+"_parsed.txt\n"); writer.Write("mpiexec reweight_tree.awk "+jobName+"_parsed.txt "+jobName+"_parsed.txt > "+jobName+"_rwt.txt \n"); writer.Write("mpiexec divisiderum_postparse_totaldown.pl root "+jobName+"_rwt.txt > "+jobName+"_down.txt \n"); writer.Write("mpiexec apomorphy_andtable_test_statistic_cox.pl "+jobName+"_rwt.txt "+jobName+"_down.txt > "+jobName+"_stat.txt\n"); writer.Write("awk '($1 != $2 && ($3+$4) > 3 && $3 > $5 && ($3-$10)/sqrt($10) >=sqrt(6)){print;}' "+jobName+"_stat.txt > "+jobName+"_stat_p0.05.txt\n"); writer.Write("awk '($1 != $2 && ($3+$4) > 3 && $3 > $5 && ($3-$10)/sqrt($10) >=sqrt(19)){print;}' "+jobName+"_stat.txt > "+jobName+"_stat_p0.001.txt\n"); writer.Write("awk '($1 != $2 && ($3+$4) > 3 && $3 > $5 && ($3-$10)/sqrt($10) >=sqrt(200)){print;}' "+jobName+"_stat.txt > "+jobName+"_stat_p0.0001.txt\n"); writer.Write("wget "+postBackURL+ " \n"); writer.Write(" echo the end time is `date`\n"); } sftp.Put(dir); sftp.Close(); //I could not Ftp to put the files in the right directory so I put them in the base and moved them with a ssh command SshStream shell = getShell(); shell.Write(string.Format("mv {0} {2}{1}/{0} ;", "GenPhenBatch.job", jobId.ToString(),DataPath)); shell.Write(string.Format("cd {1}{0} ;", jobId.ToString(),DataPath)); //echo `qstat | awk '/supramap/ {print $1}'` //shell.Write(string.Format("qsub -W depend=afterok:{0} GenPhenBatch.job",pbs_id)); //please excuese the uglness of haveing code nested in code nested in code. //awk is nest in bash that is nested in C# shell.Write(string.Format("qsub -W depend=afterany:`qstat | awk '/poy_{0}/ {{split($1,array,\".\");print array[1]}}'` GenPhenBatch.job",jobId.ToString())); File.Delete(dir); //sftp.Get("poy_test.o4281361",@"C:\temp\poy_test.o4281361"); //FileStream fileStream = File.OpenRead(@"C:\temp\poy_test.o4281361"); //byte[] filedata = new byte[(int)fileStream.Length]; //fileStream.Read(filedata,0,(int)fileStream.Length); return "Success"; }
public string Submit(int jobId, int numberOfNodes, int wallTimeHours, int wallTimeMinutes, string postBackURL) { if (wallTimeMinutes >= 60) return "Minutes must be less then 60"; if (wallTimeHours >= 99) return "Hours must be less then 99"; if (numberOfNodes >= 101) return "Number of Nodes must be less then 101"; if (numberOfNodes < 1) return "you need at least 1 node"; if (wallTimeHours < 0 || wallTimeMinutes < 0) return "We currently don't support time travel at this time"; Sftp sftp = new Sftp(HostName, UserName, Password); sftp.Connect(); string dir = string.Format(@"{0}batch.job", tempDir); using (StreamWriter writer = new StreamWriter(dir, false)) { writer.Write(string.Format("#PBS -l walltime={0}:{1}:00 \n", wallTimeHours.ToString().PadLeft(2,'0'), wallTimeMinutes.ToString().PadLeft(2,'0') )); if(superComputer.HostName=="glenn.osc.edu") writer.Write(string.Format("#PBS -l nodes={0}:ppn=12 \n",numberOfNodes)); else if(superComputer.HostName=="superdev.bmi.ohio-state.edu") writer.Write("#PBS -l nodes=5:ppn=8+4:ppn=4 \n" ); else writer.Write(string.Format("#PBS -l nodes={0} \n",numberOfNodes)); writer.Write("#PBS -N poy_" + jobId.ToString() + " \n"); writer.Write("#PBS -j oe \n"); //writer.Write("#PBS –o output.txt \n"); //writer.Write("#PBS -S /bin/ksh \n"); if(superComputer.HostName!="superdev.bmi.ohio-state.edu") writer.Write("PATH="+PoyPath+":$PATH \n"); writer.Write(string.Format("cd {0}{1}/ \n", DataPath,jobId)); writer.Write("echo the start time is `date`\n"); if(superComputer.HostName=="superdev.bmi.ohio-state.edu") //writer.Write(string.Format("mpirun -np $NUM_PROC -machinefile $PBS_NODEFILE --mca btl tcp,self --mca btl_tcp_if_include eth0 {0}poy -plugin {0}supramap.cmxs *.poy \n",superComputer.PluginPath)); writer.Write("mpirun -np 56 -machinefile $PBS_NODEFILE --mca btl tcp,self --mca btl_tcp_if_include eth0 poy_mpi -plugin /usr/local/poy-4.1.2/bin/supramap_mpi.cmxs *.poy \n"); else writer.Write(string.Format("mpiexec {0}poy -plugin {0}supramap.cmxs *.poy \n",superComputer.PluginPath)); writer.Write("wget "+postBackURL+ " \n"); writer.Write(" echo the end time is `date`\n"); } sftp.Put(dir); sftp.Close(); //I could not Ftp to put the files in the right directory so I put them in the base and moved them with a ssh command SshStream shell = getShell(); shell.Write(string.Format("mv {0} {2}{1}/{0} ;", "batch.job", jobId.ToString(),DataPath)); shell.Write(string.Format("cd {1}{0} ;", jobId.ToString(),DataPath)); shell.Write("qsub batch.job"); File.Delete(dir); //sftp.Get("poy_test.o4281361",@"C:\temp\poy_test.o4281361"); //FileStream fileStream = File.OpenRead(@"C:\temp\poy_test.o4281361"); //byte[] filedata = new byte[(int)fileStream.Length]; //fileStream.Read(filedata,0,(int)fileStream.Length); return "Success"; }
public override DTSExecResult Execute(Connections connections, VariableDispenser variableDispenser, IDTSComponentEvents componentEvents, IDTSLogging log, object transaction) { ConnectionManager cSSH = getConnectionManager(connections, _SSHconnMgrName); List<KeyValuePair<string, string>> connParams = (List<KeyValuePair<string, string>>)cSSH.AcquireConnection(transaction); string host = connParams.Find(t => t.Key == "Host").Value; string username = connParams.Find(t => t.Key == "Username").Value; string password = connParams.Find(t => t.Key == "Password").Value; int port = Convert.ToInt32(connParams.Find(t => t.Key == "Port").Value); if (_operation == SSHFTPOperation.SendFiles) { ConnectionManager cSend = getConnectionManager(connections, _sendFilesSourceConnectionManagerName); string sourceFile = cSend.AcquireConnection(transaction).ToString(); SshTransferProtocolBase sshCp; sshCp = new Sftp(host, username); sshCp.Password = password; string localFile = sourceFile; string remoteFile = getRemotePathAndFile(_sendFilesDestinationDirectory, Path.GetFileName(sourceFile)); try { sshCp.Connect(); sshCp.Put(localFile, remoteFile); } catch { throw; } finally { sshCp.Close(); } } if (_operation == SSHFTPOperation.ReceiveFiles) { ConnectionManager cReceive = getConnectionManager(connections, _receiveFilesDestinationConnectionManagerName); string destinationDirectory = cReceive.AcquireConnection(transaction).ToString(); SshTransferProtocolBase sshCp; sshCp = new Sftp(host, username); sshCp.Password = password; try { sshCp.Connect(); sshCp.Get(_receiveFilesSourceFile, destinationDirectory); } catch { throw; } finally { sshCp.Close(); } } return DTSExecResult.Success; }
//RFG 2.20 | This method will upload RI file into HPE sftp location private static bool upload_to_ftp_HPE(string fName) { string Hostname = utility.getParameter("crm_ftp_host_HPE"); string dir_path = utility.getParameter("crm_ftp_dir_HPE"); string Username = utility.getParameter("crm_ftp_user_HPE"); string Password = utility.getParameter("crm_ftp_pwd_HPE"); Sftp sftpClient = new Sftp(Hostname, Username, Password); Hashtable h_params = new Hashtable(); bool upload_success; bool changed_dir; try { //NETsFTP.SFTP.Upload(Hostname, dir_path, Username, Password, path_to_file); sftpClient.Connect(22); if (sftpClient.Connected) { } sftpClient.Put(fName, dir_path); sftpClient.Close(); upload_success = true; return upload_success; } catch (DirectoryNotFoundException e) { h_params["submit_flag"] = "crm_submit"; h_params["failure_reason"] = String.Format("FTP ERROR - {0}{1}", utility.newline, e.ToString().Replace("\r\n", "")); DB.execProc("insert_failed_submit", h_params); changed_dir = false; return changed_dir; } catch (Exception e) { h_params["submit_flag"] = "crm_submit"; h_params["failure_reason"] = String.Format("GENERAL ERROR - {0}", e.ToString().Replace("\r\n", "")); DB.execProc("insert_failed_submit", h_params); upload_success = false; return upload_success; } }
//This method was implemented in order to eliminate RFG's previous ChilkatFTP //dependency. It uses a custom SFTP class (NETsFTP) to upload the files. //Fabian Gutierrez 07/23/2008. private static bool upload_to_ftp(string fName) { //Chilkat.Ftp2 ftp = ChilkatComponents.ChilkatFtp2; //ftp.Hostname = utility.getParameter("crm_ftp_host"); string Hostname = utility.getParameter("crm_ftp_host"); string dir_path = utility.getParameter("crm_ftp_dir"); //ftp.Username = utility.getParameter("crm_ftp_user"); string Username = utility.getParameter("crm_ftp_user"); //ftp.Password = utility.getParameter("crm_ftp_pwd"); string Password = utility.getParameter("crm_ftp_pwd"); Sftp sftpClient = new Sftp(Hostname, Username, Password); //socks einstellen funktioniert nicht?! //ftp.Proxy = "socks-server.grenoble.hp.com"; Hashtable h_params = new Hashtable(); //bool connected = ftp.Connect(); //bool connected; bool upload_success; bool changed_dir; try { //NETsFTP.SFTP.Upload(Hostname, dir_path, Username, Password, path_to_file); sftpClient.Connect(22); if (sftpClient.Connected) { } sftpClient.Put(fName, dir_path); sftpClient.Close(); upload_success = true; return upload_success; } catch (DirectoryNotFoundException e) { h_params["submit_flag"] = "crm_submit"; h_params["failure_reason"] = String.Format("FTP ERROR - {0}{1}", utility.newline, e.ToString().Replace("\r\n", "")); DB.execProc("insert_failed_submit", h_params); changed_dir = false; return changed_dir; } //catch (TimeoutException e) //{ // h_params["submit_flag"] = "crm_submit"; // h_params["failure_reason"] = String.Format("FTP ERROR - {0}{1}", utility.newline, e.ToString().Replace("\r\n", "")); // DB.execProc("insert_failed_submit", h_params); // connected = false; // return connected; //} catch (Exception e) { h_params["submit_flag"] = "crm_submit"; h_params["failure_reason"] = String.Format("GENERAL ERROR - {0}", e.ToString().Replace("\r\n", "")); DB.execProc("insert_failed_submit", h_params); upload_success = false; return upload_success; } /*if (!connected) { h_params["submit_flag"] = "crm_submit"; h_params["failure_reason"] = String.Format("FTP ERROR - {0}{1}", utility.newline, ftp.LastErrorText.Replace("\r\n", "")); DB.execProc("insert_failed_submit", h_params); return connected; } bool changed_dir = false; changed_dir = ftp.ChangeRemoteDir(dir_path); if (!changed_dir) { h_params["submit_flag"] = "crm_submit"; h_params["failure_reason"] = String.Format("FTP ERROR - {0}{1}", utility.newline, ftp.LastErrorText.Replace("\r\n", "")); DB.execProc("insert_failed_submit", h_params); return changed_dir; } // Upload a file to the FTP server. bool upload_success = ftp.PutFile(path_to_tempdir, filename); if (!upload_success) { h_params["submit_flag"] = "crm_submit"; h_params["failure_reason"] = ftp.LastErrorText.Replace("\r\n", ""); DB.execProc("insert_failed_submit", h_params); return upload_success; }*/ //return true; }
//=========================================== UpLoadFile =========================================== public bool sftpUpload(string fromFilePath, string toFilePath) { GlobalVM.Instance.updateDescription(String.Format("上传文件: {0} -> {1}", fromFilePath, toFilePath)); bool bConnectSuccess = false; int nTryTime = 0; while(true) { if (nTryTime >= 3) break; try { ++nTryTime; sftpClient = new Sftp(this.sftpServerIP, this.sftpUserID, this.sftpPassword); sftpClient.Connect(16333); bConnectSuccess = true; break; } catch (Exception e) { MessageBox.Show(e.Message); } } if (bConnectSuccess) { //sftpClient.OnTransferProgress sftpClient.Put(fromFilePath, toFilePath); sftpClient.Close(); } else { MessageBox.Show("连接服务器失败!"); } return bConnectSuccess; }
private void button3_Click(object sender, EventArgs e) { if (theFiles == null) { MessageBox.Show("Please select a folder"); return; } WebClient wc = new WebClient(); wc.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore); Dictionary<string, string> serverVer = new Dictionary<string, string>(); wc.Proxy = null; try { string toparse = wc.DownloadString(hashesLoc); using (StringReader sr = new StringReader(toparse)) { string thisLine; while ((thisLine = sr.ReadLine()) != null) { if (thisLine.Contains('|')) { string[] splitted = thisLine.Split('|'); serverVer.Add(splitted[0], splitted[1]); } } } } catch (Exception ex) { //MessageBox.Show("Error parsing website, " + ex); //return; Console.WriteLine("Error parsing website, will overwrite everything."); } using (StreamWriter fs = new StreamWriter("hashes.html", false)) { foreach (var s in theFiles) { fs.WriteLine(s.Key + "|" + s.Value); } } var sftp = new Sftp(hostName.Text, User.Text, pass.Text); sftp.OnTransferProgress += new FileTransferEvent(sftp_OnTransferProgress); sftp.Connect(); foreach (var file in theFiles) { if (serverVer.ContainsKey(file.Key)) { if (serverVer[file.Key] == file.Value) { Console.WriteLine("skipped " + file.Key); continue; } } if (file.Key.Contains('\\')) { //FileInfo fi = new FileInfo(dirToHash + "\\" + file.Key); //file.Key.Split(""); string[] splitted = file.Key.Split('\\'); string dirr = root; for (int i = 0; i < splitted.Length - 1; i++) { dirr += splitted[i] + "/"; bool mkdir = false; try { sftp.GetFileList(dirr); } catch (Exception) { mkdir = true; Console.WriteLine("Making directory " + dirr); } if (mkdir) { try { sftp.Mkdir(dirr); } catch (Exception exc) { Console.WriteLine("exception with " + dirr + " while making the dir " + exc); } } } } string changed = file.Key.Replace('\\', '/'); sftp.Put(dirToHash + "\\" + file.Key, root + changed); Console.WriteLine("Sent {0} to {1}", dirToHash + "\\" + file.Key, root + changed); } sftp.Put("hashes.html", root + "hashes.html"); Console.WriteLine("Send hashes.html"); // foreach (string s in sftp.GetFileList("/")) // { // Console.WriteLine(s); // } // sftp. // sftp.Put("test.html","/var/www/test.html"); sftp.Close(); /* FtpWebRequest fRequest = (FtpWebRequest)WebRequest.Create("ftp://proxima-centauri.dreamhost.com/"); //fRequest.Method = WebRequestMethods.Ftp Ftp fRequest.Credentials = new NetworkCredential("aevv", "matteh11F"); Stream ftpStream = fRequest.GetRequestStream(); */ }
public void ShareChat(int storyid) { // check to see if the Sharechat feed is active // if Yes, create the RSS record and send it out string m_headline = ""; string m_story = ""; string m_active = ""; String connectionString = ConfigurationManager.ConnectionStrings["azureConnectionString"].ConnectionString; try { // Connect to the database and run the query. SqlConnection con = new SqlConnection(connectionString); string strSQL = "Select headline,body from story where storyid = " + storyid; SqlCommand cmd = new SqlCommand(strSQL, con); cmd.CommandType = CommandType.Text; con.Open(); SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { m_headline = (dr["headline"].ToString()); m_story = (dr["body"].ToString()); } cmd.Dispose(); con.Close(); con.Dispose(); } catch (Exception) { // The connection failed. Display an error message. //Message.Text = "Unable to connect to the database."; } try { // Connect to the database and run the query. SqlConnection con = new SqlConnection(connectionString); string strSQL = "Select active from customermessage where customerid = '5' and active = 'Y'"; SqlCommand cmd = new SqlCommand(strSQL, con); cmd.CommandType = CommandType.Text; con.Open(); SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { m_active = (dr["active"].ToString()); TimeZoneInfo timeZoneInfo; //Set the time zone information to New Zealand Standard Time timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("New Zealand Standard Time"); //Get date and time in New Zealand Standard Time var m_nzdate = TimeZoneInfo.ConvertTimeFromUtc(System.DateTime.UtcNow, timeZoneInfo); var m_id = Convert.ToString(storyid); string m_RSS_File = m_nzdate.ToString("yyyMMddHHmmss") + "-" + m_id + "RSS.xml"; string pathToFiles = Server.MapPath("/Stories/"); string RSS_FilePath = Path.Combine(pathToFiles, m_RSS_File); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; string[] lines = m_story.Replace("\r", "").Split('\n'); string m_embargoed = string.Empty; m_headline = m_headline.Replace("\r", string.Empty); // write the RSS file for ShareChat // string[] rsslines = m_story.Replace("\r", "").Split('\n'); string m_body = string.Empty; foreach (string str in rsslines) { if (str.Length > 1) { m_body += "<p> "; m_body += str; m_body += " </p>"; } } var currentdate = m_nzdate.ToString("yyyy-MM-dd HH:mm:ss"); XmlTextWriter objX = new XmlTextWriter(RSS_FilePath, Encoding.UTF8); objX.WriteStartDocument(); objX.WriteStartElement("rss"); objX.WriteAttributeString("version", "2.0"); objX.WriteStartElement("channel"); objX.WriteElementString("title", "BusinessDesk"); objX.WriteElementString("link", "http://businessdesk.co.nz/"); objX.WriteElementString("description", "BusinessDesk News Feed"); objX.WriteElementString("copyright", "(c) 2012, Content Ltd. All rights reserved."); objX.WriteElementString("ttl", "5"); objX.WriteStartElement("item"); objX.WriteElementString("title", m_headline); objX.WriteElementString("description", m_body); objX.WriteElementString("link", "http://www.businessdesk.co.nz/"); objX.WriteElementString("pubDate", currentdate); objX.WriteEndElement(); objX.WriteEndElement(); objX.WriteEndElement(); objX.WriteEndDocument(); objX.Flush(); objX.Close(); try { // Send message to ShareChat using SFTP // SshTransferProtocolBase sshCp; sshCp = new Sftp("www.sharechat.co.nz", "root"); sshCp.Password = "******"; sshCp.Connect(); string lfile = RSS_FilePath; string rfile = "/root/BusinessDesk/" + m_RSS_File; sshCp.Put(lfile, rfile); sshCp.Close(); } catch (Exception ex) { } } } catch (Exception) { // The connection failed. Display an error message. //Message.Text = "Unable to connect to the database."; } }
public bool AddZipFile(int jobId, byte[] fileData, string filename) { if(filename.Contains("/")) return false; //fail for securety //if (filename.Contains(' ')) return false; //fail for securety string dir = string.Format(@"{0}{1}.zip", tempDir, filename); Sftp sftp = new Sftp(HostName, UserName,Password); sftp.Connect(); File.WriteAllBytes(dir, (byte[]) fileData); sftp.Put(dir,DataPath+'/'+jobId+'/'); SshStream shell = getShell(); shell.Write(string.Format("unzip {2}{1}/{0}.zip", filename, jobId.ToString(),DataPath)); shell.Write(string.Format("rm {2}{1}/{0}.zip", filename, jobId.ToString(),DataPath)); File.Delete(dir); return true; }
protected void APN_Send(int msgid, string m_ftp_host, string m_ftp_username, string m_ftp_password, string m_sftp_path) { var m_msgid = msgid.ToString(); string m_msg_file = m_msgid + ".xml"; string m_fileroot = "http://businessdesk.blob.core.windows.net/messages/"; string m_file = m_fileroot + m_msg_file; CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=businessdesk;AccountKey=zWYFxlr7zhbMhXLptJ2lvtrORvoPTVunsDAf/v8B0tDsUWMigwFOJs9wEZ62XU6UdFWM1BQJ/SN9dZ0JsWVlpw=="); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("messages"); CloudBlockBlob blockBlob = container.GetBlockBlobReference(m_msg_file); string pathToFiles = Server.MapPath("/Stories/"); string m_File = pathToFiles + m_msg_file; using (var fileStream = File.OpenWrite(m_File)) { blockBlob.DownloadToStream(fileStream); } try { SshTransferProtocolBase sshCpAPN; sshCpAPN = new Sftp("ftp1.apnz.co.nz", "ContentLtd"); sshCpAPN.Password = "******"; sshCpAPN.Connect(); string lfile = m_File; string rfile = "/incoming/" + m_msg_file; sshCpAPN.Put(lfile, rfile); sshCpAPN.Close(); } catch (Exception ex) { //LogError("SFTP - Sharechat", ex.Message); } }
private void button1_Click(object sender, EventArgs e) { string makefile = HKLibrary.UTIL.HKFileHelper.GetCurrentDirectory(); string sDirPath; sDirPath = makefile + "\\data"; DirectoryInfo di = new DirectoryInfo(sDirPath); if (di.Exists == false) { di.Create(); } string PinCode = "41302903000002"; makefile = makefile + "\\data\\"+PinCode+".png"; Int32 OrderSeq = 406359; string folderName = Convert.ToString(OrderSeq); string ftpfileName = folderName + "/" + PinCode + ".jpg"; string ftpBasicPath = "/var/www/IMAGE/Web/upload/order/barcode"; //string ftpBasicPath = "/var/www/IMAGE/Web/upload/order/qrcode/"; QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M); QrCode qrCode = qrEncoder.Encode(PinCode); var renderer = new GraphicsRenderer(new FixedCodeSize(400, QuietZoneModules.Zero), Brushes.Black, Brushes.White); MemoryStream ms = new MemoryStream(); renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, ms); var image = new Bitmap(Image.FromStream(ms), new Size(new Point(200, 200))); image.Save(makefile, ImageFormat.Png); Tamir.SharpSsh.Sftp sftp; sftp = new Tamir.SharpSsh.Sftp("ledev.leisureq.co.kr", "lion", "gkffl1!"); sftp.Connect(10004); ArrayList res = sftp.GetFileList("/"); sftp.Mkdir(ftpBasicPath + "/" + folderName+ "/"); sftp.Put(makefile, ftpBasicPath + "/" + ftpfileName); sftp.Close(); //BarcodeLib.Barcode b = new BarcodeLib.Barcode(); //b.Encode(BarcodeLib.TYPE.CODE128, PinCode); //b.SaveImage(makefile, BarcodeLib.SaveTypes.JPG); /* string date = "2015-05-20 17:16:44"; string[] datePartPath = new string[4]; DateTime dt = Convert.ToDateTime(date); datePartPath[0] = dt.ToString("yyyy"); datePartPath[1] = dt.ToString("MM"); datePartPath[2] = dt.ToString("dd"); datePartPath[3] = Convert.ToString(OrderSeq); for(Int32 i =0; i<datePartPath.Length; i++){ ftpBasicPath = ftpBasicPath + "/" + datePartPath[i]; } comwls.image_01_FileMake(ftpBasicPath); */ string ftpUri = "sftp://ledev.leisureq.co.kr:10004/"+ ftpBasicPath + folderName; HKLibrary.comwls.comwls.image_01_FileMake(ftpBasicPath + folderName); FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUri); request.Method = WebRequestMethods.Ftp.MakeDirectory; //request.Method = WebRequestMethods.Ftp.UploadFile; // This example assumes the FTP site uses anonymous logon. request.Credentials = new NetworkCredential("lion", "gkffl1!"); FtpWebResponse response = (FtpWebResponse)request.GetResponse(); Stream ftpStream = response.GetResponseStream(); ftpStream.Close(); response.Close(); /* string ftpUri = "ftp://121.78.127.40:21/" + ftpBasicPath + folderName; FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUri); request.Method = WebRequestMethods.Ftp.MakeDirectory; // This example assumes the FTP site uses anonymous logon. request.Credentials = new NetworkCredential("infobay", "info9887"); FtpWebResponse response = (FtpWebResponse)request.GetResponse(); Stream ftpStream = response.GetResponseStream(); ftpStream.Close(); response.Close(); ftpUri = "ftp://121.78.127.40:21/" + ftpBasicPath + ftpfileName; request = (FtpWebRequest)WebRequest.Create(ftpUri); request.Method = WebRequestMethods.Ftp.UploadFile; // This example assumes the FTP site uses anonymous logon. request.Credentials = new NetworkCredential("infobay", "info9887"); byte[] fileContents = File.ReadAllBytes(makefile); request.ContentLength = fileContents.Length; request.UsePassive = true; Stream requestStream = request.GetRequestStream(); requestStream.Write(fileContents, 0, fileContents.Length); requestStream.Close(); response = (FtpWebResponse)request.GetResponse(); response.Close(); //sftp.ConnectTimeoutMs = 15000; //sftp.IdleTimeoutMs = 15000; //string hostname = "ftp://ledev.leisureq.co.kr:10004/"; //bool success = sftp.Connect(hostname, 10004); */ }