4 заметки с тегом

c#

Simple console tg sender with args

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;


namespace TelegramSender
{
    class Program
    {
        static void Main(string[] args)
        {
            var url = $"https://api.telegram.org/bot{key}/sendMessage?chat_id={id}&text=Успешно скачано: {args[0]}";
            WebClient client = new WebClient();
            WebProxy wp = new WebProxy("http://url:port");
            client.Proxy = wp;
            string str = client.DownloadString(url);

        }
        
    }
}
5 ноября   api   c#   telegram

Создание локальных пользователей.

Program

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.DirectoryServices.AccountManagement;
using System.Diagnostics;
using System.Reflection;
using System.IO;


namespace UsersCreator
{
    static class Program
    {
        /// <summary>
        /// Главная точка входа для приложения.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }

        public static void CreateLocalWindowsAccount(string username, string password, string displayName, string description, bool canChangePwd, bool pwdExpires)
        {            
            {
                PrincipalContext context = new PrincipalContext(ContextType.Machine);
                UserPrincipal user = new UserPrincipal(context);
                user.SetPassword(password);
                user.DisplayName = displayName;
                user.Name = username;
                user.Description = description;
                user.UserCannotChangePassword = canChangePwd;
                user.PasswordNeverExpires = pwdExpires;
                user.Save();                

                GroupPrincipal group = GroupPrincipal.FindByIdentity(context, "Пользователи");
                group.Members.Add(user);
                group.Save();

                string exeDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                Directory.SetCurrentDirectory(exeDir);
                Process process = new Process();
                process.StartInfo.FileName = "tscmd.exe";
                process.StartInfo.Arguments = $"localhost {user} TimeoutDisconnect 1";
                process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                process.Start();
                process.WaitForExit();// Waits here for the process to exit.
            }
        }

        public static string generate()
        {
            string high = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            string low = "abcdefghijklmnopqrstuvwxyz";
            string numbers = "1234567890";
            string password = "";

            Random rnd = new Random();
            password += high[rnd.Next(0, high.Length)];
            for (int i = 1; i < 7; i++)
            {
                password += low[rnd.Next(0, low.Length)];
            }

            password += numbers[rnd.Next(0, numbers.Length)];

            return password;
        }
    }
}

Form

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace UsersCreator
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int startuser = Convert.ToInt32(numericUpDown2.Value);
            for (int i = 0; i < numericUpDown1.Value; i++)
            {
                string currpass = Program.generate();
                Program.CreateLocalWindowsAccount($"{textBox2.Text + startuser}", currpass, $"{textBox2.Text + startuser}", $"{textBox2.Text + startuser}", true, true);
                textBox1.AppendText($"{textBox2.Text + startuser} {currpass}{System.Environment.NewLine}");
                startuser++;
                
            }
        }
    }
}
2018   c#

Выключение Windows сервера по звонку. Клиентская часть. v3.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WinSCP;
using System.Diagnostics;
using System.Net;
using System.Net.Mail;
using System.IO;

namespace RedButtonChecker
{
    class Program
    {
        public static void SendMail(string smtpServer, string from, string userName, string password, string mailto, string caption, string message, string attachFile = null)
        {
            try
            {
                MailMessage mail = new MailMessage();
                mail.From = new MailAddress(from);
                mail.To.Add(new MailAddress(mailto));
                mail.Subject = caption;
                mail.Body = message;
                if (!string.IsNullOrEmpty(attachFile))
                    mail.Attachments.Add(new Attachment(attachFile));
                SmtpClient client = new SmtpClient();
                client.Host = smtpServer;
                client.Port = 587;
                client.EnableSsl = false;
                client.Credentials = new NetworkCredential(userName, password);
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.Send(mail);
                mail.Dispose();
                StringBuilder sbmail = new StringBuilder();
                sbmail.Append(String.Format("{0} Message sent to {1}", DateTime.Now, mailto) + System.Environment.NewLine);
                File.AppendAllText("log.txt", sbmail.ToString());
                sbmail.Clear();
            }
            catch (Exception e)
            {
                throw new Exception("Mail.Send: " + e.Message);
            }
        }

        static void Main(string[] args)
        {
            StringBuilder sbmain = new StringBuilder();

            SessionOptions sessionOptions = new SessionOptions
            {
                Protocol = Protocol.Ftp,
                HostName = "ftpip",
                UserName = "ftpuser",
                Password = "ftppass",
            };

            Session session = new Session();
            session.Open(sessionOptions);

            if (session.FileExists("test.tmp"))
            {
                sbmain.Append(String.Format("{0} Flag exists, deleting and doing our work!{1}", DateTime.Now, System.Environment.NewLine));
                File.AppendAllText("log.txt", sbmain.ToString());
                sbmain.Clear();
                session.RemoveFiles("test.tmp");
                Process.Start("shutdown", "/s /t 10");
                SendMail("mailsrv", "from", "login", "password", "to", "Test server is shutting down", "Shutdown report");
            }
            return;
        }
    }
}
2018   c#

Создание paping для клиента.

using (var client = new WebClient())
            {
                client.DownloadFile("http://webpath/to/paping.exe", "paping.exe");
            }

            string text = "paping.exe -p " + textBox2.Text + " -c " + textBox3.Text + " " + textBox1.Text + " >result.txt";
            System.IO.File.WriteAllText(@"Start.bat", text);

            var archive = $@"{DateTime.Now.Ticks}.zip";

            using (FileStream fs = new FileStream(archive, FileMode.Create))
            using (ZipArchive arch = new ZipArchive(fs, ZipArchiveMode.Create))
            {
                arch.CreateEntryFromFile(@"paping.exe", "paping.exe");
                arch.CreateEntryFromFile(@"Start.bat", "Start.bat");
            }

            var ftpUsername = "user";
            var ftpPassword = "pass";

            using (WebClient client = new WebClient())
            {
                client.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
                client.UploadFile(string.Format("ftp://ftpip/papings/{0}", archive), WebRequestMethods.Ftp.UploadFile, archive);
            }

            System.IO.File.Delete(archive);
            System.IO.File.Delete("paping.exe");
            System.IO.File.Delete("Start.bat");

            Clipboard.SetText("Добрый день! \n\n" + "Ссылка на программу для тестирования связи с Вашим облачным сервером: " + string.Format("https://path/to/web/papings/{0}", archive) + "\nСкачайте данный архив, распакуйте и запустите файл \"Start\", откроется черное окно, после его закрытия в папке появится файл result.txt, пришлите его нам.");
            MessageBox.Show("Всё необходимое в буфере обмена!");
2018   c#