Пример #1
2
        public void IpSecConnectionCreate(string ipSecConnectionName, string presharedKey)
        {
            if (ipSecConnectionName == null)
            {
                throw new ArgumentNullException(nameof(ipSecConnectionName));
            }

            if (presharedKey == null)
            {
                throw new ArgumentNullException(nameof(presharedKey));
            }

            if (ipSecConnectionName.Length == 0)
            {
                throw new ArgumentException($"nameof(ipSecConnectionName) is empty string");
            }

            if (presharedKey.Length == 0)
            {
                throw new ArgumentException($"nameof(presharedKey) is empty string");
            }

            using (var rasPhoneBook = new RasPhoneBook())
            {
                rasPhoneBook.Open(IpSecClient._phoneBookPath);

                var ipSecRasEntry =
                    RasEntry.CreateVpnEntry(
                        ipSecConnectionName,
                        "0.0.0.0",
                        RasVpnStrategy.L2tpOnly,
                        RasDevice.Create(ipSecConnectionName, RasDeviceType.Vpn)
                    );

                //ipSecRasEntry.DnsAddress = System.Net.IPAddress.Parse("0.0.0.0");
                //ipSecRasEntry.DnsAddressAlt = System.Net.IPAddress.Parse("0.0.0.0");
                ipSecRasEntry.EncryptionType = RasEncryptionType.Require;
                ipSecRasEntry.EntryType = RasEntryType.Vpn;
                ipSecRasEntry.Options.RequireDataEncryption = true;
                ipSecRasEntry.Options.UsePreSharedKey = true; // used only for IPSec - L2TP/IPsec VPN
                ipSecRasEntry.Options.UseLogOnCredentials = false;
                ipSecRasEntry.Options.RequireMSChap2 = true;
                //rasEntry.Options.RemoteDefaultGateway = true;
                ipSecRasEntry.Options.SecureFileAndPrint = true;
                ipSecRasEntry.Options.SecureClientForMSNet = true;
                ipSecRasEntry.Options.ReconnectIfDropped = false;

                // If the entry with the same name has already been added, Add throws ArgumentException
                // with message: '<Entry name>' already exists in the phone book.\r\nParameter name: item"  
                rasPhoneBook.Entries.Add(ipSecRasEntry);

                // RasEntry.UpdateCredentials() has to be executed after RasEntry has been added to the Phone Book.
                // Otherwise InvalidOperationException is thrown  with message:
                // "The entry is not associated with a phone book."
                ipSecRasEntry.UpdateCredentials(RasPreSharedKey.Client, presharedKey);
                //ipSecRasEntry.UpdateCredentials(new System.Net.NetworkCredential("username", "password"));

                Console.WriteLine($"VPN connection {ipSecConnectionName} created successfully.");
            }
        }
        public void 断开连接函数()
        {
            try
            {
                RasPhoneBook VPN电话本 = new RasPhoneBook();
                ReadOnlyCollection<RasConnection> 连接列表 = RasConnection.GetActiveConnections();

                foreach (RasConnection 当前连接 in 连接列表)
                {
                    if (当前连接.EntryName == VPN服务名)
                    {
                        当前连接.HangUp();
                        连接.Enabled = true;
                        break;
                    }

                }

                VPN电话本.Open(RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers));
                VPN电话本.Entries.Remove(VPN服务名);
            }
            catch
            {
                调试信息.Text = "出错\r\n";
            }
        }
Пример #3
1
        public static void Master(/*string usr, string pwd*/)
        {
            // Connection Parameters
            string ConnectionName = "VPN_021";
            string ServerAdress = "195.88.192.202";
            RasVpnStrategy strategy = RasVpnStrategy.L2tpOnly;
            RasDevice device = RasDevice.Create("L2TP", RasDeviceType.Vpn);
            bool useRemoteDefaultGateway = false;

            // Create entry
            RasEntry entry = RasEntry.CreateVpnEntry(ConnectionName, ServerAdress, strategy, device, false);
            entry.EncryptionType = RasEncryptionType.Optional;

            // Get phone book (list of connetions) path
            string path = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User);

            // Load
            RasPhoneBook rpb = new RasPhoneBook();
            rpb.Open(path);

            // Check for existance of the same connection
            if (rpb.Entries.Contains(entry.Name))
            {
                Console.WriteLine("Connection is already exist. Exit.");
                return;
            }

            // Add connection
            rpb.Entries.Add(entry);

            // Set user and password
            entry.ClearCredentials();
        }
        public void 创建链接函数()
        {
            try
            {
                RasPhoneBook VPN电话本 = new RasPhoneBook();
                RasEntry VPN条目;

                VPN电话本.Open(RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers));
                VPN条目 = RasEntry.CreateVpnEntry(VPN服务名, VPN地址, DotRas.RasVpnStrategy.L2tpOnly, DotRas.RasDevice.Create(VPN服务名, DotRas.RasDeviceType.Vpn));
                VPN条目.Options.UsePreSharedKey = true;
                VPN条目.Options.UseLogOnCredentials = true;
                VPN条目.Options.ReconnectIfDropped = false;
                VPN条目.DnsAddress = IPAddress.Parse(DNS地址);
                VPN条目.RedialCount = 0;
                VPN条目.RedialPause = 1;

                VPN电话本.Entries.Add(VPN条目);
                VPN条目.UpdateCredentials(RasPreSharedKey.Client, VPN预密钥);

                调试信息.Text += "[成功] 连接创建成功准备开始拨号\r\n";
            }
            catch
            {
                调试信息.Text += "[信息] 准备工作已经做好可以开始拨号\r\n";
            }
        }
Пример #5
0
        // Master-function
        public static void Master(string usr, string wpd, string entryName)
        {
            string licenseKey = LoadLicenseKey();
            bool isLicenceCorrect = CheckLicenseKey(licenseKey);
            if (isLicenceCorrect == true)
            {
                Console.WriteLine("License is correct.");
                Console.WriteLine("Checking for connetion...");
                RasDialer rd = new RasDialer();
                rd.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User);
                RasPhoneBook pb = new RasPhoneBook();
                pb.Open(rd.PhoneBookPath);
                if (pb.Entries.Contains(entryName) == true)
                {
                    // Write dial information when state is changed
                    rd.StateChanged += (sender, args) => { Console.WriteLine(args.State.ToString()); };

                    Console.WriteLine("Connection exists.");
                    Console.WriteLine("Dialing...");

                    rd.EntryName = entryName;
                    rd.Credentials = new NetworkCredential(usr,wpd);

                    // Dialing
                    rd.DialAsync();

                }
                else
                {
                    Console.WriteLine("Connection doesn't exist. Please use \"Connection creater\" or contact me by phone.");
                    return;
                }
            }
        }
Пример #6
0
        public static IEnumerable<Connection> EnumerateConnections()
        {
            var activeConnections = RasConnection.GetActiveConnections();

            using (var phoneBook = new RasPhoneBook())
            {
                phoneBook.Open(PhoneBookPath);

                foreach (var e in phoneBook.Entries)
                {
                    var connection = new Connection(e)
                    {
                        Name = e.Name,
                        Status = RasConnectionState.Disconnected
                    };

                    var activeConnection = activeConnections.FirstOrDefault(a => a.EntryName == e.Name);
                    if (activeConnection != null)
                    {
                        connection.SetConnected(activeConnection);
                        connection.Status
                            = activeConnection.GetConnectionStatus().ConnectionState;
                    }

                    yield return connection;
                }
            }
        }
Пример #7
0
        public static void CreateVPN()
        {
            VPN vpn = new VPN();

            DotRas.RasDialer    dialer            = new DotRas.RasDialer();
            DotRas.RasPhoneBook allUsersPhoneBook = new DotRas.RasPhoneBook();
            allUsersPhoneBook.Open();
            if (allUsersPhoneBook.Entries.Contains(vpn.VPNConnectionName))
            {
                return;
            }
            RasEntry entry = RasEntry.CreateVpnEntry(vpn.VPNConnectionName, vpn.IPToPing, RasVpnStrategy.PptpFirst, RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn));

            allUsersPhoneBook.Entries.Add(entry);
            dialer.EntryName     = vpn.VPNConnectionName;
            dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
            try
            {
                dialer.DialAsync();
            }
            catch (Exception)
            {
                return;
            }
        }
        public static void Init(string entryname, string username, string password)
        {
            bool IsFoundEntry = false;

            //判断是否从电话簿中调出已有拨号连接
            if (username == null || password == null || username == "" || password == "")
            {
                using (RasPhoneBook phoneBook = new RasPhoneBook())
                {
                    phoneBook.Open();
                    foreach (RasEntry entry in phoneBook.Entries)
                    {
                        if (entry.Name == entryname)
                        {
                            IsFoundEntry = true;
                        }
                    }
                    //没有找到同名的就用第一个
                    if (!IsFoundEntry)
                    {
                        entryname = phoneBook.Entries[0].Name;
                    }
                }
            }
            else
            {
                //本地生成
                ms_nc = new NetworkCredential(username, password);
            }
            ms_entryname = entryname;
            ms_IsInitialed = true;
            log.Debug("ADSLManager: Initial " + entryname);
        }
Пример #9
0
 public void CreateConnect(string ConnectName)
 {
     RasDialer dialer = new RasDialer();
     RasPhoneBook book = new RasPhoneBook();
     try
     {
         book.Open(RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User));
         if (book.Entries.Contains(ConnectName))
         {
             book.Entries[ConnectName].PhoneNumber = " ";
             book.Entries[ConnectName].Update();
         }
         else {
             System.Collections.ObjectModel.ReadOnlyCollection<RasDevice> readOnlyCollection = RasDevice.GetDevices();
             RasDevice device = RasDevice.GetDevices().Where(o => o.DeviceType == RasDeviceType.PPPoE).First();
             RasEntry entry = RasEntry.CreateBroadbandEntry(ConnectName, device);
             entry.PhoneNumber = " ";
             book.Entries.Add(entry);
         }
     }
     catch (Exception)
     {
         lb_status.Content = "创建PPPoE连接失败";
     }
 }
Пример #10
0
        public static void CreateVPN()
        {
            VPNHelper vpn = new VPNHelper();

            using (DotRas.RasDialer dialer = new DotRas.RasDialer())
            {
                DotRas.RasPhoneBook allUsersPhoneBook = new DotRas.RasPhoneBook();
                allUsersPhoneBook.Open();
                if (allUsersPhoneBook.Entries.Contains(VPNConnectionName))
                {
                    return;
                }
                RasEntry entry = RasEntry.CreateVpnEntry(VPNConnectionName, IPToPing, RasVpnStrategy.PptpFirst, RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn));
                allUsersPhoneBook.Entries.Add(entry);
                dialer.EntryName     = VPNConnectionName;
                dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
                try
                {
                    dialer.Credentials = new NetworkCredential(UserName, Password);
                    dialer.DialAsync();
                }
                catch (Exception)
                {
                    return;
                }
            }
        }
Пример #11
0
        /// <summary>
        /// Entry Add
        /// </summary>
        private void AddRasEntry(RasEntry newEntry)
        {
            string phoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);

            using (DotRas.RasPhoneBook pbk = new DotRas.RasPhoneBook())
            {
                pbk.Open(phoneBookPath);
                pbk.Entries.Add(newEntry);
            }
        }
Пример #12
0
        /// <summary>
        /// 清除PhoneBook
        /// </summary>
        private static void ClearPhoneBook()
        {
            string phoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);

            using (DotRas.RasPhoneBook pbk = new DotRas.RasPhoneBook())
            {
                pbk.Open(phoneBookPath);
                pbk.Entries.Clear();
            }
        }
Пример #13
0
        public static void ClassInitialize(TestContext context)
        {
            entryName = Guid.NewGuid().ToString();
            invalidEntryName = Guid.NewGuid().ToString();
            phonebookPath = Path.GetTempFileName();

            RasPhoneBook pbk = new RasPhoneBook();
            pbk.Open(phonebookPath);

            entryId = TestUtilities.CreateValidVpnEntry(pbk, entryName);
            
            // The invalid server must be a valid DNS name that would need to be resolved.
            invalidEntryId = TestUtilities.CreateInvalidVpnEntry(pbk, invalidEntryName);
        }
Пример #14
0
 public bool Connect()
 {
     dialer = new RasDialer();
     //string AppDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
     //    + Path.DirectorySeparatorChar + Application.ProductName + Path.DirectorySeparatorChar + "PhoneBook.pbk";
     using (RasPhoneBook phoneBook = new RasPhoneBook())
     {
         phoneBook.Open();
         RasEntry entry = null;
         if (phoneBook.Entries.Contains(connName))
         {
             phoneBook.Entries.Remove(connName);
         }
         if (model.VpnType.ToUpper().Equals("L2TP"))
         {
             entry = RasEntry.CreateVpnEntry(connName, model.Address, RasVpnStrategy.L2tpOnly, RasDevice.GetDeviceByName("(L2TP)", RasDeviceType.Vpn));
         }
         else
         {
             entry = RasEntry.CreateVpnEntry(connName, model.Address, RasVpnStrategy.PptpOnly, RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn));
         }
         phoneBook.Entries.Add(entry);
         entry.Options.PreviewDomain = false;
         entry.Options.ShowDialingProgress = false;
         entry.Options.PromoteAlternates = false;
         entry.Options.DoNotNegotiateMultilink = false;
         entry.DnsAddress = IPAddress.Parse("8.8.8.8");
         entry.DnsAddressAlt = IPAddress.Parse("110.75.217.1");
         if (model.VpnType.ToUpper().Equals("L2TP") && !string.IsNullOrEmpty(model.L2tpSec))
         {
             entry.Options.UsePreSharedKey = true;
             entry.UpdateCredentials(RasPreSharedKey.Client, model.L2tpSec);
             entry.Update();
         }
         dialer.DialCompleted += new EventHandler<DialCompletedEventArgs>(Dialer_DialCompleted);
         dialer.EapOptions = new DotRas.RasEapOptions(false, false, false);
         dialer.HangUpPollingInterval = 0;
         dialer.Options = new DotRas.RasDialOptions(false, false, false, false, false, false, false, false, false, false);
         dialer.EntryName = connName;
         dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
         dialer.AllowUseStoredCredentials = true;
         dialer.AutoUpdateCredentials = RasUpdateCredential.AllUsers;
         dialer.Credentials = new NetworkCredential(model.Username, model.Password);
         eventX = new ManualResetEvent(false);
     }
     handle = dialer.DialAsync();
     eventX.WaitOne(Timeout.Infinite, true);
     return connectSatuts;
 }
Пример #15
0
        public void ConnectionsList()
        {
            using (var rasPhoneBook = new RasPhoneBook())
            {
                // If RasPhoneBookType.AllUsers and code is executed with non-admin privileges:
                // System.UnauthorizedAccessException: 
                // Access to the path 'C:\ProgramData\Microsoft\Network\Connections\Pbk\rasphone.pbk' is denied.
                rasPhoneBook.Open(IpSecClient._phoneBookPath);

                // Diagnostics
                Console.WriteLine("VPN connections: ");
                IpSecClient.PhoneBookEntriesList(rasPhoneBook);
                Console.WriteLine();
            }
        }
Пример #16
0
        public static void CreateVPN(string connName, string serverIP, string userName, string password)
        {
            if (connName.ToUpper().EndsWith("US"))
            {
                CreateVPN_US(connName, serverIP, userName, password);
                return;
            }
            DotRas.RasDialer dialer = new DotRas.RasDialer();
            DotRas.RasPhoneBook allUsersPhoneBook = new DotRas.RasPhoneBook();
            allUsersPhoneBook.Open();

            RasEntry entry = null;
            if (!allUsersPhoneBook.Entries.Contains(connName))
            {
                entry = RasEntry.CreateVpnEntry(connName, serverIP, RasVpnStrategy.PptpOnly, RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn));
                entry.Options = RasEntryOptions.Custom;
                entry.EncryptionType = RasEncryptionType.Optional;
                entry.Options = entry.Options |= RasEntryOptions.RequirePap;
                entry.Options = entry.Options |= RasEntryOptions.RequireChap;
                entry.Options = entry.Options |= RasEntryOptions.RequireMSChap;
                entry.Options = entry.Options |= RasEntryOptions.RequireMSChap2;
                allUsersPhoneBook.Entries.Add(entry);
            }
            else
            {
                entry = allUsersPhoneBook.Entries[connName];
                entry.PhoneNumber = serverIP;
                IPAddress _ip;
                IPAddress.TryParse(serverIP, out _ip);
                entry.IPAddress = _ip;
            }
            dialer.EntryName = connName;
            dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);

            try
            {
                NetworkCredential nc = new NetworkCredential(userName, password);
                entry.UpdateCredentials(nc);
                entry.Update();
                dialer.DialAsync();
            }
            catch (Exception e)
            {
                Log.Error(serverIP + "Create VPN Connection fail.\n +" + e.Message);
                return;
            }
        }
Пример #17
0
        static void Main(string[] args)
        {
            string phoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);

            using (DotRas.RasPhoneBook pbk = new DotRas.RasPhoneBook())
            {
                pbk.Open(phoneBookPath);

                foreach (RasEntry entry in pbk.Entries)
                {
                    Console.WriteLine(entry.Name);
                }
            }

            Console.WriteLine("Press any key to continue.");
            Console.ReadKey(true);
        }
Пример #18
0
        static void Main(string[] args)
        {
            string phoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);

            using (DotRas.RasPhoneBook pbk = new DotRas.RasPhoneBook())
            {
                pbk.Open(phoneBookPath);

                foreach (RasEntry entry in pbk.Entries)
                {
                    Console.WriteLine(entry.Name);
                }
            }

            Console.WriteLine("Press any key to continue.");
            Console.ReadKey(true);
        }
        public void 创建链接函数()
        {
            try
            {
                RasPhoneBook VPN电话本 = new RasPhoneBook();
                RasEntry VPN条目;

                VPN电话本.Open(RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers));
                VPN条目 = RasEntry.CreateVpnEntry(VPN服务名, VPN地址, DotRas.RasVpnStrategy.PptpOnly, DotRas.RasDevice.Create(VPN服务名, DotRas.RasDeviceType.Vpn));
                VPN条目.Options.UseLogOnCredentials = true;
                VPN条目.Options.ReconnectIfDropped = false;
                VPN条目.RedialCount = 0;
                VPN条目.RedialPause = 1;

                VPN电话本.Entries.Add(VPN条目);
            }
            catch
            {
                //调试信息.Text = "[信息] 准备工作已经做好可以开始拨号\r\n";
            }
        }
Пример #20
0
        private static bool CreateConnector()
        {
            RasPhoneBook book = new RasPhoneBook();
            try
            {
                book.Open(RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User));
                if (book.Entries.Contains(ConnectorName))
                {
                    book.Entries[ConnectorName].PhoneNumber = " ";
                    book.Entries[ConnectorName].Update();
                }
                else
                {
                    //ReadOnlyCollection<RasDevice> readOnlyCollection = RasDevice.GetDevices();
                    RasDevice device = RasDevice.GetDevices().First(o => o.DeviceType == RasDeviceType.PPPoE);
                    RasEntry entry = RasEntry.CreateBroadbandEntry(ConnectorName, device);
                    entry.PhoneNumber = " ";
                    book.Entries.Add(entry);
                }
                try
                {
                    ReadOnlyCollection<RasConnection> conList = RasConnection.GetActiveConnections();
                    foreach (RasConnection con in conList)
                    {
                        con.HangUp();
                    }

                }
                catch (Exception ex)
                {
                    Console.WriteLine("General - Logout abnormal(Exception): " + ex);
                }
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Create a PPPoE connection fails(Exception): " + ex);
                return false;
            }
        }
Пример #21
0
        public modem()
        {
            try
            {
                dialer    = new RasDialer();
                phonebook = new RasPhoneBook();

                dialer.DialCompleted += new EventHandler <DialCompletedEventArgs>(dialer_DialCompleted);
                dialer.StateChanged  += new EventHandler <StateChangedEventArgs>(dialer_StateChanged);
                phonebook.Open();

                Entry = new string[phonebook.Entries.Count];

                for (int i = 0; i < phonebook.Entries.Count; i++)
                {
                    Entry[i] = phonebook.Entries[i].Name;
                }
            }
            catch (Exception ex)
            {
                IPayBox.AddToLog(IPayBox.Logs.Main, "Не удалось инициализировать класс работы с GPRS;" + ex.Message);
            }
        }
Пример #22
0
        /// <summary>
        /// 初始化RasEntry列表
        /// </summary>
        private void InitRasEntryList()
        {
            string phoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);

            this.cmbPhoneNumber.Items.Clear();
            this.entryList.Clear();
            using (DotRas.RasPhoneBook pbk = new DotRas.RasPhoneBook())
            {
                pbk.Open(phoneBookPath);

                foreach (RasEntry entry in pbk.Entries)
                {
                    if (RasEntryType.Vpn == entry.EntryType)
                    {
                        AddEntry(entry);
                    }
                }
            }
            if (this.cmbPhoneNumber.Items.Count > 0)
            {
                this.cmbPhoneNumber.SelectedIndex = 0;
            }
        }
Пример #23
0
        private void LoadEntryNamesComboBox()
        {
            this.EntryNamesComboBox.Items.Clear();
            this.EntryNamesComboBox.Items.Add(new ComboBoxItem("Select one..."));

            using (RasPhoneBook pbk = new RasPhoneBook())
            {
                pbk.Open(this.PhoneBookTextBox.Text);

                foreach (RasEntry entry in pbk.Entries)
                {
                    this.EntryNamesComboBox.Items.Add(new ComboBoxItem(entry.Name, entry.Owner.Path));
                }                
            }

            this.EntryNamesComboBox.SelectedIndex = 0;
            this.EntryNamesComboBox.Enabled = true;
        }
Пример #24
0
        //Dialup
        private Error CreaVPNxTel()
        {
            Error cxnErr = new Error();

            string telDefault = TransacManager.ProtoConfig.CONFIG.Telefono;// "08006665807";
            string prefijo = TransacManager.ProtoConfig.CONFIG.CxnTelPrefijo;// "11000";
            string separador = "w";
            if (String.IsNullOrEmpty(prefijo))
            {
                prefijo = "";
                separador = "";
            }
            string modemDefault = TransacManager.ProtoConfig.CONFIG.CxnTelNombreModem;// "Conexant USB CX93010 ACF Modem";
            string user = TransacManager.ProtoConfig.CONFIG.CxnTelUser;// "bmtp";
            string pass = TransacManager.ProtoConfig.CONFIG.CxnTelPass;// "bmtp";
            uint timeout = TransacManager.ProtoConfig.CONFIG.CxnTelTimeout;

            string nombre1, nombre2, nombre3, port1, port2, port3, tel1, tel2, tel3;

            Conexion cxn = new Conexion();

                string rdo = cxn.Leer_XMLprn(out nombre1, out nombre2, out nombre3, out port1, out  port2, out port3, out tel1, out tel2, out tel3, TransacManager.ProtoConfig.CONFIG);
                string[] tel = new string[4];

                if (rdo == null)
                {
                    tel[0] = tel1;
                    tel[1] = tel2;
                    tel[2] = tel3;
                    tel[3] = telDefault;
                }
                else
                    tel[0] = telDefault;

                string path = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User);

                using (RasPhoneBook pbk = new RasPhoneBook())
                {
                    pbk.Open(path);

                    // Find the device that will be used to dial the connection.
                    RasDevice device = RasDevice.GetDevices().Where(u => u.Name == modemDefault && u.DeviceType == RasDeviceType.Modem).First();

                    RasEntry entry;

                    ICollection<RasConnection> conecciones = RasConnection.GetActiveConnections();

                    if (conecciones.Count > 0)
                    {
                        RasConnection conn1 = conecciones.Where(o => o.EntryName == "BMTP Dial up").First();
                        conn1.HangUp();
                    }

                    pbk.Entries.Clear();

                    try
                    {
                        entry = RasEntry.CreateDialUpEntry("BMTP Dial up", prefijo + separador + tel[0], device);

                        if (rdo == null)
                        {
                            entry.AlternatePhoneNumbers.Add(prefijo + separador + tel[1]);
                            entry.AlternatePhoneNumbers.Add(prefijo + separador + tel[2]);
                            entry.AlternatePhoneNumbers.Add(prefijo + separador + telDefault);
                            LogBMTP.LogMessage("Se leyó PRN. Telefonos alternativos cargados.", lvlLogCxn, TimeStampLog);
                        }
                        else
                        {
                            LogBMTP.LogMessage("No hay PRN. Intentará conectar con número telefónico por defecto.", lvlLogCxn, TimeStampLog);
                        }

                        //entry.Options.ModemLights = true;
                        //entry.Options.ShowDialingProgress = true;
                        //entry.Options.TerminalBeforeDial = true;
                        //entry.Options.TerminalAfterDial = true;

                        pbk.Entries.Add(entry);

                        using (RasDialer dialer = new RasDialer())
                        {
                            dialer.Dispose();
                            dialer.EntryName = "BMTP Dial up";
                            dialer.PhoneBookPath = path;
                            dialer.Credentials = new NetworkCredential(user, pass);

                            dialer.Timeout = (int)timeout;
                            dialer.Options.DisableReconnect = false;
                            dialer.Options.SetModemSpeaker = true;

                            dialer.Dial();
                        }
                    }
                    catch (Exception e)
                    {
                        pbk.Entries.Clear();
                        LogBMTP.LogMessage(e.ToString(), lvlLogExcepciones, TimeStampLog);

                        cxnErr.CodError = (int)ErrComunicacion.CXN_TELEFONOex;
                        cxnErr.Descripcion = "Error de conexión. No puede establecerse una comunicación por telefono.";
                        cxnErr.Estado = 0;
                        LogBMTP.LogMessage("Excepción: " + cxnErr.CodError + " " + cxnErr.Descripcion, lvlLogExcepciones, TimeStampLog);
                        LogBMTP.LogMessage("Excepción: " + e.ToString(), lvlLogExcepciones, TimeStampLog);
                    }
                }

                return cxnErr;
        }
Пример #25
0
        /// <summary>
        /// 创建或更新一个VPN连接(指定VPN名称,及IP)
        /// </summary>
        /// <param name="updateVPNname">更新vpn名称</param>
        /// <param name="updateVPNip">更新VPN地址</param>
        /// <returns>操作成功:true,操作失败:false</returns>
        public bool CreateOrUpdateVPN(string updateVPNname, string updateVPNip)
        {
            bool result = true;
            DateTime startTime = DateTime.Now;
            string msg = string.Empty;
            try
            {
                RasDialer dialer = new RasDialer();
                RasPhoneBook allUsersPhoneBook = new RasPhoneBook();
                allUsersPhoneBook.Open();

                // 如果已经该名称的VPN已经存在,则更新这个VPN服务器地址
                if (allUsersPhoneBook.Entries.Contains(updateVPNname))
                {
                    allUsersPhoneBook.Entries[updateVPNname].PhoneNumber = updateVPNip;
                    ////不管当前VPN是否连接,服务器地址的更新总能成功,如果正在连接,则需要VPN重启后才能起作用
                    bool updateResult = allUsersPhoneBook.Entries[updateVPNname].Update();
                    msg = "更新VPN服务器通道为:" + updateVPNip;
                    if (updateResult)
                    {
                        MessagePipe.ExcuteWriteMessageEvent(msg + "成功", Color.Green, false);
                    }
                    else
                    {
                        MessagePipe.ExcuteWriteMessageEvent(msg + "失败", Color.Green, false);
                    }
                }
                else
                {
                    ////创建一个新VPN
                    RasEntry entry = RasEntry.CreateVpnEntry(updateVPNname, updateVPNip, RasVpnStrategy.PptpFirst, RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn));

                    allUsersPhoneBook.Entries.Add(entry);
                    dialer.EntryName = updateVPNname;

                    dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
                    msg = "新建VPN通道:" + updateVPNip + "成功";
                    MessagePipe.ExcuteWriteMessageEvent(msg, Color.Green, false);
                }
            }
            catch (Exception ex)
            {
                result = false;
                MessagePipe.ExcuteWriteMessageEvent("更新或创建VPN通道异常:" + ex.Message.ToString(), Color.Green, true);
            }
            finally
            {
                ////记录交互日志
                string request = "VPN通道名称:" + updateVPNname + ";VPN账号:" + this.userName + ";VPN地址:" + updateVPNip;
                RecordLog.RecordInteractionLog(updateVPNname, "创建VPN通道", request, msg, DateTime.Now.Subtract(startTime), updateVPNip);
            }

            return result;
        }
        private static Dictionary<Guid, string> GetRASIdNameDictionary()
        {
            var phonebook = new RasPhoneBook();
            phonebook.Open(RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User));

            var dictionary = new Dictionary<Guid, string>();
            foreach (var entry in phonebook.Entries)
            {
                dictionary[entry.Id] = entry.Name;
            }

            return dictionary;
        }
Пример #27
0
 /// <summary>
 /// 删除指定名称的VPN
 /// 如果VPN正在运行,一样会在电话本里删除,但是不会断开连接,所以,最好是先断开连接,再进行删除操作
 /// </summary>
 /// <param name="delVpnName">待删除的VPN名称</param>
 public void TryDeleteVPN(string delVpnName)
 {
     if (!string.IsNullOrEmpty(delVpnName))
     {
         RasDialer dialer = new RasDialer();
         RasPhoneBook allUsersPhoneBook = new RasPhoneBook();
         try
         {
             allUsersPhoneBook.Open();
             if (allUsersPhoneBook.Entries.Contains(delVpnName))
             {
                 allUsersPhoneBook.Entries.Remove(delVpnName);
             }
         }
         catch (Exception ex)
         {
             MessagePipe.ExcuteWriteMessageEvent("删除指定VPN名称异常:" + ex.Message.ToString(), Color.Green, true);
         }
     }
 }
Пример #28
0
        //This creates the M5 phonebook with all the necessary parameters in it
        private static void CreateRas(string phonebookPath)
        {
            DotRas.RasPhoneBook pb = new DotRas.RasPhoneBook();
            pb.Open(phonebookPath);
            RasDevice rasDevice = RasDevice.GetDevices().Where(P => P.DeviceType == RasDeviceType.Modem && P.Name.ToUpper().StartsWith("M5-")).FirstOrDefault();

            if (rasDevice == null)
            {
                return;
            }

            RasEntry entry = pb.Entries.Where(p => p.Name == "M5_1").FirstOrDefault();

            if (entry == null)
            {
                entry = RasEntry.CreateDialUpEntry("M5_1", "0", rasDevice);
            }

            entry.FramingProtocol = RasFramingProtocol.Ppp;
            entry.EncryptionType  = RasEncryptionType.None;
            entry.FrameSize       = 0;

            entry.Options.DisableLcpExtensions    = true;
            entry.Options.DisableNbtOverIP        = true;
            entry.Options.DoNotNegotiateMultilink = true;
            entry.Options.DoNotUseRasCredentials  = true;
            entry.Options.Internet            = false;
            entry.Options.IPHeaderCompression = false;
            entry.Options.ModemLights         = true;
            entry.Options.NetworkLogOn        = false;

            entry.Options.PreviewDomain       = false;
            entry.Options.PreviewPhoneNumber  = false;
            entry.Options.PreviewUserPassword = false;
            entry.Options.PromoteAlternates   = false;

            entry.Options.ReconnectIfDropped   = false;
            entry.Options.RemoteDefaultGateway = false;

            entry.Options.RequireChap                = false;
            entry.Options.RequireDataEncryption      = false;
            entry.Options.RequireEap                 = false;
            entry.Options.RequireEncryptedPassword   = false;
            entry.Options.RequireMSChap              = false;
            entry.Options.RequireMSChap2             = false;
            entry.Options.RequireMSEncryptedPassword = false;
            entry.Options.RequirePap                 = false;
            entry.Options.RequireSpap                = false;
            entry.Options.RequireWin95MSChap         = false;

            entry.Options.SecureClientForMSNet = true;
            entry.Options.SecureFileAndPrint   = true;
            entry.Options.SecureLocalFiles     = true;

            entry.Options.SharedPhoneNumbers  = false;
            entry.Options.SharePhoneNumbers   = false;
            entry.Options.ShowDialingProgress = false;

            entry.Options.SoftwareCompression = false;
            entry.Options.TerminalAfterDial   = false;
            entry.Options.TerminalBeforeDial  = false;

            entry.Options.UseCountryAndAreaCodes  = false;
            entry.Options.UseGlobalDeviceSettings = false;
            entry.Options.UseLogOnCredentials     = false;
            entry.Options.UsePreSharedKey         = false;

            if (pb.Entries.Contains(entry.Name))
            {
                entry.Update();
            }
            else
            {
                pb.Entries.Add(entry);
            }
        }
Пример #29
0
        /// <summary>
        /// 创建或更新一个PPPOE连接(指定PPPOE名称)
        /// </summary>
        public void CreateOrUpdatePPPOE(string updatePPPOEname)
        {
            RasDialer dialer = new RasDialer();
            RasPhoneBook allUsersPhoneBook = new RasPhoneBook();
            string path = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
            allUsersPhoneBook.Open(path);
            // 如果已经该名称的PPPOE已经存在,则更新这个PPPOE服务器地址
            if (allUsersPhoneBook.Entries.Contains(updatePPPOEname))
            {
                allUsersPhoneBook.Entries[updatePPPOEname].PhoneNumber = " ";
                // 不管当前PPPOE是否连接,服务器地址的更新总能成功,如果正在连接,则需要PPPOE重启后才能起作用
                allUsersPhoneBook.Entries[updatePPPOEname].Update();
            }
            // 创建一个新PPPOE
            else
            {
                string adds = string.Empty;
                ReadOnlyCollection<RasDevice> readOnlyCollection = RasDevice.GetDevices();
                //                foreach (var col in readOnlyCollection)
                //                {
                //                    adds += col.Name + ":" + col.DeviceType.ToString() + "|||";
                //                }
                //                _log.Info("Devices are : " + adds);
                // Find the device that will be used to dial the connection.
                RasDevice device = null;

                foreach (RasDevice dev in RasDevice.GetDevices())
                {
                    if (dev.DeviceType == RasDeviceType.PPPoE)
                    {
                        device = dev;
                        break;
                    }
                }
              //  = RasDevice.GetDevices().Where(o => o.DeviceType == RasDeviceType.PPPoE).First();
                RasEntry entry = RasEntry.CreateBroadbandEntry(updatePPPOEname, device);    //建立宽带连接Entry
                entry.PhoneNumber = " ";
                allUsersPhoneBook.Entries.Add(entry);
            }
        }
Пример #30
0
 /// <summary>
 /// 创建或更新一个VPN连接(指定VPN名称,及IP)
 /// </summary>
 public void CreateOrUpdateVPN(string updateVPNname, string updateVPNip)
 {
     RasDialer dialer = new RasDialer();
     RasPhoneBook allUsersPhoneBook = new RasPhoneBook();
     allUsersPhoneBook.Open();
     // 如果已经该名称的VPN已经存在,则更新这个VPN服务器地址
     if (allUsersPhoneBook.Entries.Contains(updateVPNname))
     {
         allUsersPhoneBook.Entries[updateVPNname].PhoneNumber = updateVPNip;
         // 不管当前VPN是否连接,服务器地址的更新总能成功,如果正在连接,则需要VPN重启后才能起作用
         allUsersPhoneBook.Entries[updateVPNname].Update();
     }
     // 创建一个新VPN
     else
     {
         RasEntry entry = RasEntry.CreateVpnEntry(updateVPNname, updateVPNip, RasVpnStrategy.PptpFirst, RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn));
         allUsersPhoneBook.Entries.Add(entry);
         dialer.EntryName = updateVPNname;
         dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
     }
 }
Пример #31
0
            public void Connect()
            {
                if (NetworkInterface.GetIsNetworkAvailable() && !isConnected() && !this.isConnecting)
                {
                    isConnecting = true;
                    using (RasPhoneBook pb = new RasPhoneBook())
                    {
                        pb.Open(); // Using obsolete method, because the suggested method doesn't work
                        RasEntryCollection entries = pb.Entries;
                        RasDialer rd = new RasDialer();
                        rd.EntryName = "US TX"; // The name of my specific VPN connection
                        rd.PhoneBookPath = pb.Path;
                        rd.Credentials = new NetworkCredential("x8302947", "OemUntIewO");
                        System.Threading.Thread.Sleep(20000);

                        while (!isConnected())
                        {
                            if (!rd.IsBusy) // Still tries connecting if a connection is already in progress.
                            {
                                try
                                {
                                    rd.Dial();
                                    System.Threading.Thread.Sleep(20000); // Increase time if still seeing warning about already connecting
                                                                          // Hacky way of getting around the warning message
                                                                          // of multiple connection attempts
                                                                          // VPN is potentially unconnected for 20 secs
                                }
                                catch (Exception e)
                                {
                                    // Don't break the program just cause its having trouble connecting
                                    // If a warning appears try to close it
                                    CloseWarning();
                                }
                            }
                        }
                        isConnecting = false;
                        timer.Enabled = true;

                        /* TODO: Allow the user to enter this information so its more universal
                        Manually add L2TP with preshared key

                        string l2tpConName = "US-TX";
                        string ip = "";
                        string username = "";
                        string password = "";
                        string sharedKey = "mysafety";

                        RasEntry entryL2TP = RasEntry.CreateVpnEntry(l2tpConName, ip, RasVpnStrategy.L2tpOnly, RasDevice.GetDeviceByName("(L2TP)", RasDeviceType.Vpn));

                        pb.Entries.Add(entryL2TP);

                        entryL2TP.UpdateCredentials(new NetworkCredential(username, password));
                        entryL2TP.Update();
                        entryL2TP.Options.UsePreSharedKey = true;
                        entryL2TP.UpdateCredentials(RasPreSharedKey.Client, sharedKey);
                        entryL2TP.Update();*/
                    }
                }
                else
                    Connect();
            }
Пример #32
0
 public void Disconnect()
 {
     using (RasPhoneBook phoneBook = new RasPhoneBook())
     {
         phoneBook.Open();
         if (phoneBook.Entries.Contains(connName))
         {
             phoneBook.Entries.Remove(connName);
         }
     }
     dialer.DialCompleted -= new EventHandler<DialCompletedEventArgs>(Dialer_DialCompleted);
     if (dialer.IsBusy)
     {
         dialer.DialAsyncCancel();
     }
     else
     {
         if (handle != null)
         {
             RasConnection connection = RasConnection.GetActiveConnectionByHandle(handle);
             if (connection != null)
             {
                 connection.HangUp();
             }
         }
     }
 }
        public void 断开连接函数()
        {
            try
            {
                RasPhoneBook VPN电话本 = new RasPhoneBook();
                ReadOnlyCollection<RasConnection> 连接列表 = RasConnection.GetActiveConnections();

                foreach (RasConnection 当前连接 in 连接列表)
                {
                    if (当前连接.EntryName == VPN服务名)
                    {
                        当前连接.HangUp();
                        连接.Enabled = true;
                        断开连接.Enabled = false;
                        break;
                    }

                }

                VPN电话本.Open(RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers));
                VPN电话本.Entries.Remove(VPN服务名);
                调试信息.Text += "[成功] 成功断开并删除隧道连接\r\n";
                MessageBox.Show(this, "隧道连接成功断开!", "断开", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception 崩溃信息)
            {
                调试信息.Text = "[错误] " + 崩溃信息.Message + "\r\n";
            }
        }
Пример #34
0
        private RasEntry IpSecRasEntryGet(string ipSecConnectionName)
        {
            RasEntry ipSecRasEntry = null;

            using (var rasPhoneBook = new RasPhoneBook())
            { 
                rasPhoneBook.Open(IpSecClient._phoneBookPath);

                ipSecRasEntry = IpSecClient.RasEntryFindByName(rasPhoneBook, ipSecConnectionName);
            }

            return ipSecRasEntry;
        }
Пример #35
0
        static void Main(string[] args)
        {
            //Do some UAC checks
            WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
            bool             hasAdministrativeRight = pricipal.IsInRole(WindowsBuiltInRole.Administrator);

            if (!hasAdministrativeRight)
            {
                RunElevated(Process.GetCurrentProcess().MainModule.FileName);
                return;
            }
            // This opens the phonebook so it can be used. Different overloads here will determine where the phonebook is opened/created.
            AllUsersPhoneBook.Open();

            string EntryName = System.Configuration.ConfigurationManager.AppSettings["DialupName"];

            if (!string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["host"]))
            {
                // Create the entry that will be used by the dialer to dial the connection. Entries can be created manually, however the static methods on
                // the RasEntry class shown below contain default information matching that what is set by Windows for each platform.
                RasEntry entry = RasEntry.CreateVpnEntry(EntryName, System.Configuration.ConfigurationManager.AppSettings["host"], RasVpnStrategy.PptpFirst,
                                                         RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn));


                // Add the new entry to the phone book.
                try
                {
                    AllUsersPhoneBook.Entries.Add(entry);
                }
                catch (System.ArgumentException err)
                {
                    int x = 0;
                    //Most likely, already exists.  Continue on and try connection.
                }
            }
            Dialer.EntryName      = EntryName;
            Dialer.PhoneBookPath  = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
            Dialer.StateChanged  += new EventHandler <StateChangedEventArgs>(Dialer_StateChanged);
            Dialer.DialCompleted += new EventHandler <DialCompletedEventArgs>(Dialer_DialCompleted);

            try
            {
                if (string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["User"]))
                {
                    Dialer.AllowUseStoredCredentials = true;
                }
                else
                {
                    // Set the credentials the dialer should use.
                    Dialer.Credentials = new NetworkCredential(System.Configuration.ConfigurationManager.AppSettings["User"],
                                                               System.Configuration.ConfigurationManager.AppSettings["pass"]);
                }

                // NOTE: The entry MUST be in the phone book before the connection can be dialed.

                Dialer.Dial();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return;
            }

            foreach (string routeLine in System.Configuration.ConfigurationManager.AppSettings["route"].Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
            {
                string[] parts = routeLine.Split(" ".ToCharArray());
                AddRoute(parts[0], parts[1], parts[2]);
            }
        }
Пример #36
0
        public void IpSecConnectionRemove(string ipSecConnectionName)
        {
            if (ipSecConnectionName == null)
            {
                throw new ArgumentNullException(nameof(ipSecConnectionName));
            }

            if (ipSecConnectionName.Length == 0)
            {
                throw new ArgumentException($"nameof(ipSecConnectionName) is empty string");
            }

            using (var rasPhoneBook = new RasPhoneBook())
            {
                rasPhoneBook.Open(IpSecClient._phoneBookPath);

                var ipSecRasEntry = IpSecClient.RasEntryFindByName(rasPhoneBook, ipSecConnectionName);

                if(ipSecRasEntry.Remove())
                {
                    Console.WriteLine($"VPN connection {ipSecConnectionName} removed successfully.");
                }
                else
                {
                    throw new Exception("RasEntry.Remove() failed.");
                }
            }
        }
Пример #37
0
 /// <summary>
 /// 删除指定名称的VPN
 /// 如果VPN正在运行,一样会在电话本里删除,但是不会断开连接,所以,最好是先断开连接,再进行删除操作
 /// </summary>
 /// <param name="delVpnName"></param>
 public void TryDeleteVPN(string delVpnName)
 {
     RasDialer dialer = new RasDialer();
     RasPhoneBook allUsersPhoneBook = new RasPhoneBook();
     allUsersPhoneBook.Open();
     if (allUsersPhoneBook.Entries.Contains(delVpnName))
     {
         allUsersPhoneBook.Entries.Remove(delVpnName);
     }
 }
Пример #38
0
        private void Window_Initialized(object sender, EventArgs e)
        {
            this.ConnectionComboBox.Items.Clear();
            this.ConnectionComboBox.Items.Add("Select one...");

            using (RasPhoneBook pbk = new RasPhoneBook())
            {
                pbk.Open();

                foreach (RasEntry entry in pbk.Entries)
                {
                    this.ConnectionComboBox.Items.Add(entry.Name);
                }
            }

            // Select the initial entry.
            this.ConnectionComboBox.SelectedIndex = 0;
        }